Skip to content
Advertisement

Pandas rolling apply function to entire window dataframe

I want to apply a function to a rolling window. All the answers I saw here are focused on applying to a single row / column, but I would like to apply my function to the entire window. Here is a simplified example:

JavaScript

This is df:

JavaScript

Take some function to apply to the entire window:

JavaScript

In this example, I would like to get something like:

JavaScript

Of course, the shape is used as an example showing f treats the entire window as the object of calculation, not just a row / column. I tried playing with the axis keyword for rolling, as well as with the raw keyword for apply but with no success. Other methods (agg, transform) do not seem to deliver either.

Sure, I can do this with a list comprehension. Just thought there is an easier / cleaner way of doing this.

Advertisement

Answer

Not with pd.DataFrame.rolling …. that function is applied iteratively to the columns, taking in a series of floats/NaN, and returning a series of floats/NaN, one-by-one. I think you’ll have better luck with your intuition….

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement