Python pandas rolling_apply two column input into function

前端 未结 4 566
故里飘歌
故里飘歌 2020-12-08 05:25

Following on from this question Python custom function using rolling_apply for pandas, about using rolling_apply. Although I have progressed with my function, I

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 06:07

    Looks like rolling_apply will try to convert input of user func into ndarray (http://pandas.pydata.org/pandas-docs/stable/generated/pandas.stats.moments.rolling_apply.html?highlight=rolling_apply#pandas.stats.moments.rolling_apply).

    Workaround based on using aux column ii which is used to select window inside of manipulating function gm:

    import pandas as pd
    import numpy as np
    import random
    
    tmp = pd.DataFrame(np.random.randn(2000,2)/10000, columns=['A','B'])
    tmp['date'] = pd.date_range('2001-01-01',periods=2000)
    tmp['ii'] = range(len(tmp))            
    
    def gm(ii, df, p):
        x_df = df.iloc[map(int, ii)]
        #print x_df
        v =((((x_df['A']+x_df['B'])+1).cumprod())-1)*p
        #print v
        return v.iloc[-1]
    
    #print tmp.head()
    res = pd.rolling_apply(tmp.ii, 50, lambda x: gm(x, tmp, 5))
    print res
    

提交回复
热议问题