title: Optimize code to find the median of values of past 30 day for each row in a DataFrame
body: <p>I'd like to find faster code to achieve the same goal: for each row, compute the median of all data in the past 30 days. But there are less than 5 data points, then return <code>np.nan</code>.</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  import datetime
  
  def findPastVar(df, var='var' ,window=30, method='median'):
      # window= # of past days    
      def findPastVar_apply(row):
          pastVar = df[var].loc[(df['timestamp'] - row['timestamp'] &lt; datetime.timedelta(days=0)) &amp; (df['timestamp'] - row['timestamp'] &gt; datetime.timedelta(days=-window))]
          if len(pastVar) &lt; 5:
              return(np.nan)            
          if method == 'median':
              return(np.median(pastVar.values))
      df['past{}d_{}_median'.format(window,var)] = df.apply(findPastVar_apply,axis=1)
      return(df)
  
  
  df = pd.DataFrame()
  df['timestamp'] = pd.date_range('1/1/2011', periods=100, freq='D')
  df['timestamp'] = df.timestamp.astype(pd.Timestamp)
  df['var'] = pd.Series(np.random.randn(len(df['timestamp'])))
  </code></pre>
  
  <p>Data looks like this. In my real data, there are gaps in time and maybe more data points in one day.</p>
  
  <pre><code>In [47]: df.head()
  Out[47]: 
               timestamp       var
  0  2011-01-01 00:00:00 -0.670695
  1  2011-01-02 00:00:00  0.315148
  2  2011-01-03 00:00:00 -0.717432
  3  2011-01-04 00:00:00  2.904063
  4  2011-01-05 00:00:00 -1.092813
  </code></pre>
  
  <p>Desired output:</p>
  
  <pre><code>In [55]: df.head(10)
  Out[55]: 
               timestamp       var  past30d_var_median
  0  2011-01-01 00:00:00 -0.670695                 NaN
  1  2011-01-02 00:00:00  0.315148                 NaN
  2  2011-01-03 00:00:00 -0.717432                 NaN
  3  2011-01-04 00:00:00  2.904063                 NaN
  4  2011-01-05 00:00:00 -1.092813                 NaN
  5  2011-01-06 00:00:00 -2.676784           -0.670695
  6  2011-01-07 00:00:00 -0.353425           -0.694063
  7  2011-01-08 00:00:00 -0.223442           -0.670695
  8  2011-01-09 00:00:00  0.162126           -0.512060
  9  2011-01-10 00:00:00  0.633801           -0.353425
  </code></pre>
  
  <p>However, my current code running speed:</p>
  
  <pre><code>In [49]: %timeit findPastVar(df)
  1 loop, best of 3: 755 ms per loop
  </code></pre>
  
  <p>I need to run a large dataframe from time to time, so I want to optimize this code. </p>
  
  <p>Any suggestion or comment are welcome. </p>