You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用DataFrame下一行b列值迭代更新a列?

DataFrame列迭代更新实现方案

原始数据

import pandas as pd
df = pd.DataFrame({
    'a': [420, 380, 390],
    'b': [50, 40, 45]
})

输出结果:

a   b
0  420  50
1  380  40
2  390  45

目标效果

更新后a列以首个值420为基础,依次累加前一行的b列值,最终得到:

a   b
0  420  50
1  460  40
2  505  45

实现方法

方法1:pandas累加函数(高效推荐)

利用向量式运算替代循环,适合大数据量场景:

# 计算b列前n-1项的累加和
cum_b = df['b'].iloc[:-1].cumsum()
# 拼接初始值与累加序列,替换原a列
df['a'] = pd.concat([df['a'].iloc[:1], df['a'].iloc[0] + cum_b], ignore_index=True)

方法2:循环迭代(直观易懂)

如果需要清晰展示每一步更新逻辑,可使用基础循环:

# 从第二行开始逐行更新
for i in range(1, len(df)):
    df.loc[i, 'a'] = df.loc[i-1, 'a'] + df.loc[i-1, 'b']

方法3:shift()结合累加(简洁写法)

通过位移函数简化逻辑,一行代码完成更新:

# b列向下位移一行后累加,再加上a列初始值
df['a'] = df['a'].iloc[0] + df['b'].shift().fillna(0).cumsum()

内容的提问来源于stack exchange,提问作者Mohammad.sh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:35:48