apply a function on rolling window in Dataframe where whole dataframe is passed to function

我与影子孤独终老i 提交于 2019-12-04 09:30:50

Question: ... apply a rolling window and pass all five columns to a function

This will do what you want, min_periods=5, axis=1. .rolling(... window is column 'A':'E' or a multiple of 5.

def f1(data=None):
    print('f1(%s, %s) data=%s' % (str(type(data)), param, data))
    return data.sum()

subRates = rates.rolling(window=60, min_periods=5, axis=1).apply(lambda x: f1( x ) )

Input:

               A         B         C         D         E
YearMo
200001  0.666744  0.569194  0.546873  0.018696  0.240783
200002  0.035888  0.853077  0.348200  0.921997  0.283177
200003  0.652761  0.076630  0.298076  0.800504  0.041231
200004  0.537397  0.968399  0.211072  0.328157  0.929783
200005  0.759506  0.702220  0.807477  0.886935  0.022587

Output:

f1(<class 'numpy.ndarray'>, None) data=[ 0.66674393  0.56919434  0.54687296  0.01869609  0.24078329]
f1(<class 'numpy.ndarray'>, None) data=[ 0.03588751  0.85307707  0.34819965  0.92199698  0.28317727]
f1(<class 'numpy.ndarray'>, None) data=[ 0.65276067  0.07663029  0.29807589  0.80050448  0.04123137]
f1(<class 'numpy.ndarray'>, None) data=[ 0.53739687  0.96839917  0.21107155  0.32815687  0.92978308]
f1(<class 'numpy.ndarray'>, None) data=[ 0.75950632  0.70222034  0.80747698  0.88693524  0.02258685]
         A   B   C   D         E
YearMo
200001 NaN NaN NaN NaN  2.042291
200002 NaN NaN NaN NaN  2.442338
200003 NaN NaN NaN NaN  1.869203
200004 NaN NaN NaN NaN  2.974808
200005 NaN NaN NaN NaN  3.178726

Tested with Python:3.4.2 - pandas:0.19.2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!