[英]get cumprod() for rows in pandas pivot table
I want to calculate the geometric return (cumulative return) per annum for a pivot table containing monthly return and add this as a column to the table. 我想为包含每月收益的数据透视表计算每年的几何收益(累计收益),并将其作为列添加到表格中。 The pivot table looks like this: 数据透视表如下所示:
In [474]: piv.tail(3)
Out[474]:
month 1 2 3 4 5 6 7 8 9 10 11 12
year
2015 3.0 -5.6 1.5 -0.1 0.3 -1.7 0.5 -7.0 0.3 -0.1 0.4 0.0
2016 5.2 4.7 -0.3 1.3 -6.1 0.3 3.5 -0.1 1.2 -1.9 0.7 0.9
2017 2.5 2.1 0.1 2.6 4.8 0.1 2.8 0.1 -2.1 0.5 NaN NaN
tried 试着
piv['annual'] = (piv+1).cumprod(axis=1)-1
Which throws an error. 这引发了错误。 Stuck here. 卡在这里。 any help appreciated. 任何帮助表示赞赏。
prod
使用prod
piv.assign(annual=(piv / 100 + 1).prod(1) * 100 - 100)
Month 1 2 3 4 5 6 7 8 9 10 11 12 annual
Year
2015 3.0 -5.6 1.5 -0.1 0.3 -1.7 0.5 -7.0 0.3 -0.1 0.4 0.0 -8.600390
2016 5.2 4.7 -0.3 1.3 -6.1 0.3 3.5 -0.1 1.2 -1.9 0.7 0.9 9.272164
2017 2.5 2.1 0.1 2.6 4.8 0.1 2.8 0.1 -2.1 0.5 NaN NaN 14.156949
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.