python - pandas 当前行 * 上一行 + 上一行

标签 python pandas

索引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

关于python - pandas 当前行 * 上一行 + 上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43755327/

相关文章:

python - Paypal 整合错误

python - 将标记字符串附加到 BeautifulSoup 中的标记

python - 索引错误 : At least one sheet must be visible

python - 将 pandas 列名称从蛇形命名法转换为驼峰式命名法

python - 使用 Pandas 按指定顺序写入 Excel 表格

python - 应用引擎,Python : Send Mail function

python - TFTPy 导入,没有名为 tftpy 的模块

python - 为什么 Python 的 json.dumps 拒绝序列化我的对象中的字符串?

python - 取消聚合 Pandas 中的字符串值字段

pandas - 如何在多索引列上使用 Pandas .assign() 方法链?