聚合的数据帧复合计算

2024-09-23 06:29:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: toimportdataframepandasdfdatetimeasagg
1条回答
网友
1楼 · 发布于 2024-09-23 06:29:41

看来你需要:

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

相关问题 更多 >