pandas icon indicating copy to clipboard operation
pandas copied to clipboard

DOC: Rolling with method="table" to apply func to all columns and not just individual columns

Open joshlk opened this issue 4 years ago • 5 comments

Is your feature request related to a problem?

With a group.apply the applied function acts on all columns available to provide a result. With rolling.apply it applies the function to each column individually - it would be great if you could apply it to all the columns as well.

e.g. the following is possible with groupby.apply

df = pd.DataFrame({'A': range(10), 'B': range(10,0,-1)}).reset_index()
df['index'] = df['index'] % 3
df.groupby('index').apply(lambda df: df['A'] + df['B'])

However, you can't do the same equivalent with rolling.apply:

df = pd.DataFrame({'A': range(10), 'B': range(10,0,-1)}).reset_index()
df.rolling(3, on='index').apply(lambda df: (df['A'] * df['B']).sum())

Gives the error: KeyError: 'A'

This is because the apply function is applied to each column separately. The series is passed to the function not the dataframe. This feels inconsistent and annoying if you want to apply a function to the grouped rolling data. It would be great if there were a way to do it 😃

joshlk avatar Mar 11 '21 14:03 joshlk

seee https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.rolling.html#pandas.DataFrame.rolling

this is possible in 1.3 with method='table' and a numba udf.

jreback avatar Mar 11 '21 18:03 jreback

Hi, thanks - I must of missed that. It took me a while to work out where to add engine='numba'. Can we keep this ticket open and I will add an example to rolling API documentation?

joshlk avatar Mar 12 '21 09:03 joshlk

sure happy to have more documentation

jreback avatar Mar 12 '21 11:03 jreback

Ive added an example to the docs in #40519

joshlk avatar Mar 19 '21 17:03 joshlk

Hey there, is there a way to do it without using a numba ufunc? I'm trying to use it with a scikit-learn model and those two libraries are just not compatible at all

bachnguyen-tomo avatar May 08 '24 02:05 bachnguyen-tomo