Pandas当前行*上一行+上一行

2024-03-29 09:19:01 发布

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

索引(p):

tradedate  |  percent  |  day_index
------ | ------| ------
2015-06-02 |    0      |     1000
2015-06-03 |    0.5    |     0
2015-06-04 |    0.6    |     0
.....

想要的结果:

^{pr2}$

我尽力了

index_pd['day_index'] =index_pd['day_index'].shift(1) * index_pd['percent'].shift(0) + index_pd['day_index'].shift(1)

但它影响了第二排。 索引有上千行,如何批量替换,谢谢


Tags: indexshift批量pdpercentdaypr2tradedate
2条回答

不是很好的解决方案,因为^{}循环:

for i, row in index_pd.iterrows():
    if i == 0:
        index_pd.loc[i, 'value'] = index_pd['day_index'].iat[0]
    else:
        index_pd.loc[i, 'value'] = index_pd.loc[i,'percent']  * index_pd.loc[i-1, 'value']+ \
                                   index_pd.loc[i-1, 'value']
print (index_pd)
    tradedate  percent  day_index   value
0  2015-06-02      0.0       1000  1000.0
1  2015-06-03      0.5          0  1500.0
2  2015-06-04      0.6          0  2400.0

在计算的每一行中,前面的day_index值将乘以(1+index_pd.percent)。因此,您可以使用(1+index_pd.percent)的累积积,并将其乘以day_index的第一个值,得到结果:

index_pd['day_index'] = (index_pd.percent+1).cumprod()*index_pd.day_index.iat[0]

相关问题 更多 >