title: Looping a function over unique column id's only
body: <p>I have a code that calculates the slope of x and y variables (the theil-sen slope) and I want to run this on a list of values based on specific column values in a csv file. My file looks like this:</p>
  
  <p><code>station_id      year      Sum
    210018      1917    329.946
    210018      1918    442.214
    210018      1919    562.864
    210018      1920    396.748
    210018      1921    604.266
    210019      1917    400.946
    210019      1918    442.214
    210019      1919    600.864
    210019      1920    250.748
    210019      1921    100.266</code></p>
  
  <p>The function I am using is:</p>
  
  <pre><code>def theil_sen(x,y):
  
      n   = len(x)
      ord = numpy.argsort(x)
      xs  = x[ord]
      ys  = y[ord]
      vec1 = numpy.zeros( (n,n) )
      for ii in range(n):
          for jj in range(n):
              vec1[ii,jj] = ys[ii]-ys[jj]
      vec2 = numpy.zeros( (n,n) )
      for ii in range(n):
          for jj in range(n):
              vec2[ii,jj] = xs[ii]-xs[jj]
      v1    = vec1[vec2&gt;0]    
      v2    = vec2[vec2&gt;0]     
      slope = numpy.median( v1/v2 )
      coef  = numpy.zeros( (2,1) ) 
      b_0   = numpy.median(y)-slope*numpy.median(x)
      b_1   = slope
      res   = y-b_1*x-b_0 # residuals 
  
      return (b_0,b_1,res)
  </code></pre>
  
  <p>I want to use <code>Sum</code> as the y value in the function, <code>year</code> as the x value and only run the function on each unique <code>station_id</code> value.  My output should be:</p>
  
  <pre><code>210018: -117189, 61.29
  210019: 164382, -85.45
  </code></pre>
  
  <p>I am aware that scipy has a theil slope function, but it is an incorrect calculation.</p>
  
  <p>Thanks in advance.</p>