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

如何合并两个存在重叠的Pandas Series并将重叠行值设为0

解决方法

这里提供两种简洁的实现方式,都能满足你的需求:

方法一:拆分合并法

先分离两个Series的非重叠部分,再单独处理重叠索引的取值,最后合并所有部分并排序索引:

import pandas as pd

# 构造示例数据
A = pd.Series([1, 1, 1], index=[0, 1, 2], name='A')
B = pd.Series([2, 2, 2], index=[2, 3, 4], name='B')

# 1. 获取两个Series的重叠索引
common_idx = A.index.intersection(B.index)

# 2. 提取A、B的非重叠部分
a_non_overlap = A.drop(common_idx)
b_non_overlap = B.drop(common_idx)

# 3. 创建重叠索引对应的Series,值设为指定值(这里是0)
overlap_series = pd.Series(0, index=common_idx)

# 4. 合并所有部分并按索引排序
C = pd.concat([a_non_overlap, b_non_overlap, overlap_series]).sort_index()
C.name = 'C'

print(C)

输出结果:

0    1
1    1
2    0
3    2
4    2
Name: C, dtype: int64

方法二:分组处理法

先合并两个Series,再按索引分组,判断每组元素数量:若为2则说明是重叠索引,设置为指定值;否则保留原数值:

import pandas as pd

# 构造示例数据
A = pd.Series([1, 1, 1], index=[0, 1, 2], name='A')
B = pd.Series([2, 2, 2], index=[2, 3, 4], name='B')

# 1. 合并两个Series,重叠索引会保留两个值
combined = pd.concat([A, B])

# 2. 按索引分组处理
C = combined.groupby(combined.index).apply(lambda x: 0 if len(x) == 2 else x.iloc[0])
C.name = 'C'

print(C)

输出结果和方法一完全一致。如果需要修改重叠部分的指定值,只需要把代码中的0替换成你想要的数值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:24:47