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

Python中比较Pandas DataFrame并添加缺失行的实现方法

问题:合并Pandas DataFrame并补充缺失行

现有两个Pandas DataFrame,结构如下:

df1:

col1   col2       col3   col4
A      C0079731   s1     abc
A      C0079731   s2     abc

df2:

col1   col2       col3
A      C0079731   s1
A      C0079731   s2
AA     C0079731   s3

需求:基于col2对比,将df2中存在但df1中缺失的col3对应的行添加到df1,新增行的col4值固定为abc,预期输出:

col1   col2       col3   col4
A      C0079731   s1     abc
A      C0079731   s2     abc
AA     C0079731   s3     abc

尝试使用merge方法:df_2 = df1.merge(df2, left_on='col2', right_on = 'col2', how = 'inner'),未得到预期结果,如何实现?


解决方案

你之前的inner连接逻辑有误:一是inner只会保留两个DataFrame的交集,二是仅按col2匹配无法精准识别同一col2下缺失的col3行。正确的做法是基于col2+col3的组合来判断缺失行,以下是两种可行方法:

方法1:简洁版 - concat+去重

先给df2补充col4列,再和df1合并后去重:

import pandas as pd

# 给df2添加col4列,值为'abc'
df2_extended = df2.assign(col4='abc')
# 合并两个DataFrame,按col2和col3去重,保留首次出现的行
result = pd.concat([df1, df2_extended]).drop_duplicates(subset=['col2', 'col3'], keep='first')
# 重置索引(可选操作)
result = result.reset_index(drop=True)

方法2:直观版 - 筛选缺失行再合并

通过merge的indicator参数标记行的来源,筛选出df2独有的行后合并:

import pandas as pd

# 基于col2和col3做左连接,添加_indicator列标记行的来源
merged = df2.merge(df1[['col2', 'col3']], on=['col2', 'col3'], how='left', indicator=True)
# 筛选出仅在df2中存在的行
missing_rows = merged[merged['_indicator'] == 'left_only'].drop('_indicator', axis=1)
# 给缺失行补充col4列
missing_rows['col4'] = 'abc'
# 合并到原df1
result = pd.concat([df1, missing_rows]).reset_index(drop=True)

两种方法都能得到预期结果,方法1代码更简洁,方法2清晰展示了缺失行的筛选过程,可根据需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:06:01