Skip to main content
 首页 » 编程设计

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

2025年02月15日6pengyingh

index_pd:

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

想要的结果:

tradedate  |  percent  |  day_index 
------ | ------| ------ 
2015-06-02 |    0      |     1000 
2015-06-03 |    0.5    |     1500 = 1000 + 1000 * 0.5 
2015-06-04 |    0.6    |     2400 = 1500 + 1500 * 0.6 
..... 

我试试

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

但它影响第二行。 index_pd有几千行,如何批量替换,谢谢

请您参考如下方法:

不是很好的解决方案,因为通过 iterrows 循环:

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