title: Pandas timeseries lookback
body: <p>There is a data frame with a time series:</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  
  df = pd.DataFrame({'times': np.array(['1994-07-25 15:00:00.000',
                              '1994-07-25 16:00:00.000', 
                              '1994-07-26 18:45:00.000', 
                              '1994-07-27 15:15:00.000', 
                              '1994-07-27 16:00:00.000', 
                              '1994-07-28 18:45:00.000', 
                              '1994-07-28 19:15:00.000', 
                                       ], dtype='datetime64'),
                     'diff': [0.0,0.03,0.04,0.05,0,0.01,0.0,]})
  </code></pre>
  
  <p>the diff (between two signals) reverts to zero and I want to find out the time it was out of line for - i.e. the time for which it was non-zero -> below the wanted result</p>
  
  <pre><code>df['deviation_time_delta'] = pd.to_timedelta(['nan',
                              'nan', 
                              'nan', 
                              'nan', 
                              '2 days 00:00:00.000', 
                              'nan', 
                              '0 days 00:30:00.000', 
                                       ])
  </code></pre>
  
  <p>I have tried this - but it isn't beautiful and it doesn't work on arbitrary length deviations:</p>
  
  <pre><code>df['diff_1'] = df['diff'].shift(1)
  df['diff_2'] = df['diff'].shift(2)
  df['diff_3'] = df['diff'].shift(3)
  df['diff_4'] = df['diff'].shift(4)
  df['times_1'] = df['times'].shift(1)
  df['times_2'] = df['times'].shift(2)
  df['times_3'] = df['times'].shift(3)
  df['times_4'] = df['times'].shift(4)
  
  def calc_dev_time_delta(cur_diff, diff_1, diff_2, diff_3, diff_4, cur_time, time_1, time_2, time_3, time_4):
      if cur_diff != 0.0: return np.nan
      if diff_1 == 0.0: return np.nan
      if diff_2 == 0.0: return cur_time - time_1 
      if diff_3 == 0.0: return cur_time - time_2
      if diff_4 == 0.0: return cur_time - time_3
  
  df['dev_time_delta'] = df.apply(lambda row: calc_dev_time_delta(row['diff'], row['diff_1'], row['diff_2'],row['diff_3'],row['diff_4'], row['times'], row['times_1'], row['times_2'], row['times_3'], row['times_4']), axis=1)
  </code></pre>
  
  <p>Do you know a better/cleaner way to achieve this result?</p>