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

如何实现Pandas DataFrame特殊相加:匹配索引求和,缺失索引保留

Pandas DataFrame 按索引相加:保留非匹配索引的数值

你需要的是匹配索引对应值求和,非匹配索引直接保留原数值的DataFrame相加逻辑,下面两种方法可以完美实现需求:

方法1:使用add()方法并指定fill_value=0

add()是Pandas专门用于数据对齐的加法方法,设置fill_value=0后,仅在单个DataFrame中存在的索引会被填充0参与计算,最终结果等价于保留原数值:

import pandas as pd

# 构造示例数据
df1 = pd.DataFrame({'data': [4.2, 5.0, 3.0]}, index=['index1', 'index2', 'index3'])
df2 = pd.DataFrame({'data': [1.0, 7.0, 2.0]}, index=['index2', 'index3', 'index4'])

# 执行相加操作
result = df1.add(df2, fill_value=0)

输出结果:

data
index1   4.2
index2   6.0
index3  10.0
index4   2.0

方法2:concat结合groupby.sum()

先合并两个DataFrame,再按索引分组求和,同样能实现需求:

combined = pd.concat([df1, df2])
result = combined.groupby(combined.index).sum()

执行后得到的结果和方法1完全一致。

为什么之前的尝试没生效?

  • 直接用+运算符:会将仅单个DataFrame存在的索引对应值标记为NaN,无法保留原数值
  • 未设置fill_value的add()方法:缺失位置默认填充NaN,相加后仍为NaN
  • 单纯使用concat():仅完成数据合并,未对重复索引的值求和

内容的提问来源于stack exchange,提问作者J. C. Stark

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:52:39