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

如何对Pandas DataFrame实现重复滚动减法运算?

这个计算逻辑可以用pandas内置的累积求和函数实现,不需要手动写循环迭代,效率很高:

单列实现

你要的计算逻辑本质是:首行值保持不变,后续每行结果等于首行值减去从第二行到当前行所有原始值的和,可以用cumsum()一行实现:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({'value': [100, 1, 4, 10, 5, 3]})

# 计算结果
df['result'] = df['value'].iloc[0] * 2 - df['value'].cumsum()

输出的result列就是你要的结果:

0    100
1     99
2     95
3     85
4     80
5     77

多列批量实现

如果需要对DataFrame所有列应用该运算,直接对整个DataFrame执行上述逻辑即可,pandas会自动逐列计算:

# 多列示例数据
df_multi = pd.DataFrame({
    'col1': [100, 1, 4, 10, 5, 3],
    'col2': [200, 2, 8, 20, 10, 6]
})

# 全列应用运算
res_multi = df_multi.iloc[0] * 2 - df_multi.cumsum()

计算后每列都会按照规则生成对应结果。

内容的提问来源于stack exchange,提问作者lserlohn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:36:06