title: Python: Create an incrementing variable that changes based on a condition
body: <p>I want to create a variable called 'inc' that increments sequentially each time a condition is met (say, Delta>=5), holds the same otherwise, and resets to 1 each time it encounters a new group (ID in this example).  So here's an example dataframe:</p>
  
  <pre><code>from pandas import *
  d={'rx': [1,1,1,1,1,2,2,2,2,2],
      'vals': [1,2,3,8,10,1,10,20,21,22]}
  df=DataFrame(d)
  
  
  def diff_func(df):
      return df.diff()                                
  
  df['delta'] = df.groupby(['rx'])['vals'].apply(diff_func)  
  </code></pre>
  
  <p>Which produces this:</p>
  
  <pre><code>rx  vals delta
  1   1    NaN
  1   2    1
  1   3    1
  1   8    5
  1   10   2
  2   1    NaN
  2   10   9
  2   20   10
  2   21   1
  2   22   1
  </code></pre>
  
  <p>So now I want to create a new column called 'Event' that I will later use to group observations within each value of rx separated by a delta &lt; 5:</p>
  
  <pre><code>rx  vals    delta   Event
  1   1       NaN     1
  1   2       1       1
  1   3       1       1
  1   8       5       2
  1   10      2       2
  2   1       NaN     1
  2   10      9       2
  2   20      10      3
  2   21      1       3
  2   22      1       3
  </code></pre>
  
  <p>Note that 'event' returns to 1 on the first occurrence of rx.  I am used to doing this in vbasic or SAS, where you simply retain a value and then increment by 1 each time the threshold trigger is met.  Is there a similarly simple solution to this in Python?</p>