Apply function on a rolling slice of a pandas DataFrame

Viewed 4256

I'd like to calculate the determinant of 2x2 matrices which are taken by rolling a window of size 2 on a Nx2 matrix. I'm just using the determinant as an example function. In general, I'd like to apply a function to a dataframe which is taken by windowing a larger dataframe.

For example, this is a single 2x2 matrix and I calculate the determinant like so:

import pandas as pd
import numpy as np

d = pd.DataFrame({
   "X": [1,2],
   "Y": [3,4]
   })
np.linalg.det(d)

Now, I can form 4 2x2 matrices by sliding a window of size 2 along axis=0 of the following dataframe:

df = pd.DataFrame({
    "A": [1,2,3,4,5],
    "B": [6,7,8,9,10],
  })

which looks like:

    A   B
0   1   6
1   2   7
2   3   8
3   4   9
4   5   10

so I would get [-5., -5., -5., -5.]

As far as I can see, pandas.DataFrame.rolling and rolling.apply can only be applied on a 1D vector, not a dataframe? How would you do this?

4 Answers
Related