2017-05-03 48 views
2

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) 

但它影响第二排。 有1000行的index_pd,如何批量替换,感谢

+0

你需要写一个不同的列,如果你想保持第二的原始值行。 – TLOwater

+0

我如何批量计算? –

+0

你是指什么批次?我原来的答案是不对的,你应该将结果写入日期索引并使用结果来计算下一步。 – TLOwater

回答

1

不怎么样的解决方案,因为环路由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 
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]