using a custom function with arguments on Pandas rolling

Viewed 117

To illustrate the issue

import pandas as pd
import numpy as np    

def testfunc(x, mult=1):
    res = sum(x)*mult
    return res

series = pd.Series(np.random.rand(100), name='test')

I'd like to run 'testfunc' on rolling windows of size 10, say, of 'series' using the mult argument.

series.rolling(10).apply(testfunc, raw=False, **{'mult':2})

If i Try the above I receive an error

TypeError: apply() got an unexpected keyword argument 'mult'

it seems from the help page that this should be possible, but I can't find a working example

1 Answers

According to this doc, Series.rolling().apply() does not accept **kwargs. Instead, there's kwargs option, which takes a dictionary:

series.rolling(10).apply(testfunc, raw=False, kwargs={'mult':2})

Output:

0           NaN
1           NaN
2           NaN
3           NaN
4           NaN
        ...    
95    11.782115
96    10.999794
97     9.678652
98     9.669550
99    10.093348
Name: test, Length: 100, dtype: float64
Related