聚合的数据帧复合计算

时间:2018-02-11 09:45:26

标签: python pandas pandas-groupby

import pandas as pd

times = pd.to_datetime(pd.Series(['2014-07-4',
'2014-07-15','2014-08-25','2014-08-25','2014-09-10','2014-09-15']))

strategypercentage = [0.01, 0.02, -0.03, 0.04,0.5,-0.3]
df = pd.DataFrame({'Strategy': strategypercentage}, index=times)

##lambda x: ((1+x).cumprod()-1)


df.resample("1M").agg({'Strategy' : ['sum','prod']})

数据框包括日期和每日百分比变化,我如何计算每月百分比变化复合(看起来像((1 + x).cumprod() - 1)) - 但如何用agg实现? 预期结果: enter image description here

1 个答案:

答案 0 :(得分:0)

似乎你需要:

df['new'] = df.resample("1M")['Strategy'].apply(lambda x: ((1+x).cumprod()-1))
print (df)
            Strategy     new
2014-07-04      0.01  0.0100
2014-07-15      0.02  0.0302
2014-08-25     -0.03 -0.0300
2014-08-25      0.04  0.0088
2014-09-10      0.50  0.5000
2014-09-15     -0.30  0.0500