title: Pandas apply function to multiple columns with sliding window
body: <p>I need to calculate some metric using sliding window over dataframe. If metric needed just 1 column, I'd use <code>rolling</code>. But some how it does not work with 2+ columns.
  Below is how I calculate the metric using regular cycle.</p>
  <pre><code>def mean_squared_error(aa, bb):
      return np.sum((aa - bb) ** 2) / len(aa)
  
  def rolling_metric(df_, col_a, col_b, window, metric_fn):
      result = []
      for i, id_ in enumerate(df_.index):
          if i &lt; (df_.shape[0] - window + 1):
              slice_idx = df_.index[i: i+window-1]
              slice_a, slice_b = df_.loc[slice_idx, col_a], df_.loc[slice_idx, col_b]
              result.append(metric_fn(slice_a, slice_b))
          else:
              result.append(None)
      return pd.Series(data = result, index = df_.index)
  
  df = pd.DataFrame(data=(np.random.rand(1000, 2)*10).round(2), columns = ['y_true', 'y_pred'] )
  
  %time df2 = rolling_metric(df, 'y_true', 'y_pred', window=7, metric_fn=mean_squared_error)
  </code></pre>
  <p>This takes close to a second for just 1000 rows.</p>
  <p>Please suggest faster vectorized way to calculate such metric over sliding window.</p>