在花了几个小时努力学习如何做到这一点后,我开始接触社区
我从以下几点开始:
perf
date
2018-06-01 0.012923
2018-06-02 0.039364
2018-06-03 0.042805
2018-06-04 -0.033214
2018-06-05 -0.021745
需要计算新列的累积百分比变化,但需要确保计算使用100作为起始值。所以我在一行前面加了100:
perf pct_change
date
2018-05-31 NaN 100.0
2018-06-01 0.012923 NaN
2018-06-02 0.039364 NaN
2018-06-03 0.042805 NaN
2018-06-04 -0.033214 NaN
我需要得到的是:
perf pct_change
date
2018-05-31 NaN 100.0
2018-06-01 0.012923 101.2923
2018-06-02 0.039364 105.2795701
2018-06-03 0.042805 109.7860621
2018-06-04 -0.033214 106.1396278
公式类似于pct_change = previous_days_pct_change * ( 1 + perf )
我尝试了几种不同的方法,包括for ... in
循环,但没有成功
# INCOMPLETE/DOES NOT WORK (adding for illustration purposes only)
for index, row in performance.iterrows():
curr = performance.loc[index, 'perf']
pidx = index + pd.DateOffset(-1)
prev = performance.iloc[[pidx], 'pct_change']
performance.loc[index, 'pct_change'] = prev * ( 1 + curr )
我还尝试:
performance['pct_change'] = performance['pct_change'].shift() * ( 1 + performance['perf'] )
这将产生:
perf pct_change
date
2018-05-31 NaN NaN
2018-06-01 0.012923 101.292251
2018-06-02 0.039364 NaN
2018-06-03 0.042805 NaN
2018-06-04 -0.033214 NaN
但这只给了我一个值
我怀疑已经有一个更简单的方法来做我想做的事情,但我只是没有找到它。任何帮助都将不胜感激。在电子表格中很容易做到,但我想学习如何在熊猫中做到这一点
多谢各位
使用^{} :
实现您真正想要的:
因此,您实际上是在计算
perf
值(或者更准确地说perf + 1
值)的累积乘积像这样:
相关问题 更多 >
编程相关推荐