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

如何用最快方式计算Pandas DataFrame的累积内积?

最快实现Pandas累积乘积和的方法

原始DataFrame

AB
26
55
75
82
611

需求

计算前i行(i从1到DataFrame总行数)A、B列对应元素乘积的累积和:

  • i=1时,结果为 2*6=12
  • i=2时,结果为 2*6+5*5=37
  • i=3时,结果为 2*6+5*5+7*5=72
  • 以此类推,得到每一步的累积结果

最优实现方案

放弃Python循环,使用Pandas内置的向量化操作,这是效率最高的方式——尤其是处理大数据集时,性能远优于逐行循环。

代码实现

import pandas as pd

# 构造目标DataFrame
df = pd.DataFrame({
    'A': [2, 5, 7, 8, 6],
    'B': [6, 5, 5, 2, 11]
})

# 1. 向量化计算每行A与B的乘积
product_col = df['A'] * df['B']
# 2. 调用内置方法计算累积和
cumulative_sum = product_col.cumsum()

# 若需要将结果存入原DataFrame
df['cumulative_sumproduct'] = cumulative_sum

# 输出结果
print(df)

运行结果

ABcumulative_sumproduct
2612
5537
7572
8288
611154

关键说明

  • df['A'] * df['B']:一次性完成所有行的乘积计算,无需循环遍历,属于向量化运算
  • cumsum():Pandas底层用C实现的累积求和方法,比Python原生循环快几个数量级

如果只需要得到累积和的列表,无需修改原DataFrame,可直接:

cumulative_sum_list = (df['A'] * df['B']).cumsum().tolist()
# 结果:[12, 37, 72, 88, 154]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:21:17