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

如何获取df2中未与df1匹配的行(列不同无法合并/拼接)

解决方法

核心思路是:先把df1中用于匹配的关键列按规则整理成可快速查询的集合,再对df2每条记录做相同处理,筛选出不在这个集合里的行,完全避开列结构不同的问题。

步骤1:处理df1的匹配键

根据你的middle_name匹配约束,先把df1的三个关键列处理成唯一标识的键集合:

  • 如果约束是first_name、last_name完全匹配,middle_name也完全匹配(空值统一视为匹配):
import pandas as pd

# 先清理空值和冗余空格,生成匹配键
df1['first_clean'] = df1['first_name'].str.strip().fillna('')
df1['last_clean'] = df1['last_name'].str.strip().fillna('')
df1['middle_clean'] = df1['middle_name'].str.strip().fillna('')

# 转成集合,提升查询速度
df1_match_set = set(zip(df1['first_clean'], df1['last_clean'], df1['middle_clean']))
  • 如果约束是first_name、last_name完全匹配,middle_name非空时才需匹配,空值忽略:
# 生成适配约束的匹配键
def build_match_key(row):
    first = row['first_name'].strip() if pd.notna(row['first_name']) else ''
    last = row['last_name'].strip() if pd.notna(row['last_name']) else ''
    middle = row['middle_name'].strip() if pd.notna(row['middle_name']) else ''
    if middle:
        return (first, last, middle)
    else:
        return (first, last)

df1_match_set = set(df1.apply(build_match_key, axis=1).unique())

步骤2:筛选df2的未匹配行

用和df1完全一致的规则处理df2,然后筛选出不在匹配集合里的行:

# 用同样的逻辑处理df2
df2['match_key'] = df2.apply(build_match_key, axis=1)
# 提取未匹配的行,清理临时列
df2_unmatched = df2[~df2['match_key'].isin(df1_match_set)].drop(columns=['match_key'])

大数据量提速优化

如果df1的36.7万行用apply速度慢,可改用矢量化操作:

# 以完全匹配约束为例,矢量化生成键
df2['first_clean'] = df2['first_name'].str.strip().fillna('')
df2['last_clean'] = df2['last_name'].str.strip().fillna('')
df2['middle_clean'] = df2['middle_name'].str.strip().fillna('')

# 筛选未匹配行
df2_unmatched = df2[~df2.apply(
    lambda x: (x['first_clean'], x['last_clean'], x['middle_clean']) in df1_match_set,
    axis=1
)]
# 清理临时列
df2_unmatched = df2_unmatched.drop(columns=['first_clean', 'last_clean', 'middle_clean'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:50:29