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

Pandas合并两个DataFrame前新增列标记跨数据集重复记录方法问询

实现代码

首先导入依赖包并构造示例数据(注:示例中df_b的Toy Story导演字段疑似笔误,代码中修正为和df_a一致才能匹配为重复项):

import pandas as pd

df_a = pd.DataFrame({
    'title': ['Toy Story', 'Goodfellas', 'Meet the Fockers', 'The Departed'],
    'director': ['John Lasseter', 'Martin Scorsese', 'Jay Roach', 'Martin Scorsese']
})

df_b = pd.DataFrame({
    'title': ['Toy Story', 'The Hangover', 'Rocky', 'The Departed'],
    'director': ['John Lasseter', 'Todd Phillips', 'John Avildsen', 'Martin Scorsese']
})

小数据量实现方案

逻辑是先标记df_a中在df_b存在匹配的记录,再拼接df_b中独有的无重复记录:

# 定义判断重复的匹配列,可根据实际需求修改
match_cols = ['title', 'director']
# 提取df_b的所有匹配键集合
b_key_set = set(df_b[match_cols].itertuples(index=False, name=None))

# 给df_a添加标记列
df_a['occurence_both'] = df_a[match_cols].apply(
    lambda x: 'b' if tuple(x) in b_key_set else '', 
    axis=1
)

# 筛选df_b中不在df_a里的独有记录
a_key_set = set(df_a[match_cols].itertuples(index=False, name=None))
df_b_unique = df_b[~df_b[match_cols].apply(
    lambda x: tuple(x) in a_key_set, 
    axis=1
)].copy()
df_b_unique['occurence_both'] = ''

# 合并得到最终结果
df_result = pd.concat([df_a, df_b_unique], ignore_index=True)

大数据量高效实现方案

用merge代替逐行apply,性能更高:

match_cols = ['title', 'director']
df_b['_temp_flag'] = True

# 标记df_a中匹配到df_b的记录
df_a_tagged = df_a.merge(
    df_b[match_cols + ['_temp_flag']],
    on=match_cols,
    how='left'
)
df_a_tagged['occurence_both'] = df_a_tagged['_temp_flag'].map({True: 'b'}).fillna('')
df_a_tagged = df_a_tagged.drop('_temp_flag', axis=1)

# 筛选df_b独有的记录
df_merge_all = df_a.merge(df_b, on=match_cols, how='outer', indicator=True)
df_b_only = df_merge_all.loc[df_merge_all['_merge'] == 'right_only', match_cols].copy()
df_b_only['occurence_both'] = ''

# 合并结果
df_result = pd.concat([df_a_tagged, df_b_only], ignore_index=True)

最终输出的df_result和给出的预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:00:03