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

如何将一个DataFrame中的值累加至另一个DataFrame?

实现两个DataFrame数值累加的方法

核心思路

以Product作为匹配键,将DataFrame 2中的Amount和Price列数值累加到DataFrame 1对应行中,其他列(如Total)保持不变。

具体代码实现

先导入pandas并创建示例数据:

import pandas as pd

# 创建DataFrame 1
df1 = pd.DataFrame({
    'Product': ['A', 'B', 'C', 'D'],
    'Amount': [1, 4, 2, 5],
    'Price': [12.0, 20.0, 4.0, 30.0],
    'Total': [15, 15, 15, 15]
})

# 创建DataFrame 2
df2 = pd.DataFrame({
    'Product': ['B', 'C'],
    'Amount': [3, 2],
    'Price': [20.0, 4.0]
})

提供两种常用实现方法:

方法一:合并后逐列累加

通过合并匹配行,再对目标列执行相加操作:

# 按Product合并,保留df1所有行
merged_df = df1.merge(df2, on='Product', how='left', suffixes=('', '_df2'))

# 累加Amount和Price,空值用0填充避免计算错误
merged_df['Amount'] = merged_df['Amount'] + merged_df['Amount_df2'].fillna(0)
merged_df['Price'] = merged_df['Price'] + merged_df['Price_df2'].fillna(0)

# 移除临时生成的列,得到结果
result_df = merged_df.drop(['Amount_df2', 'Price_df2'], axis=1)

方法二:索引匹配后直接相加

通过设置索引快速匹配,代码更简洁:

# 将两个DataFrame的索引设为Product
df1_indexed = df1.set_index('Product')
df2_indexed = df2.set_index('Product')

# 对指定列执行累加,fill_value=0确保无匹配行时不改变原数据
df1_indexed[['Amount', 'Price']] = df1_indexed[['Amount', 'Price']].add(df2_indexed[['Amount', 'Price']], fill_value=0)

# 恢复原索引结构
result_df = df1_indexed.reset_index()

最终结果

执行上述代码后,result_df输出与预期一致:

ProductAmountPriceTotal
A112.015
B720.015
C44.015
D530.015

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:05:34