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

如何用Python找出两个DataFrame中第二个表缺失的id_number?

问题描述

我有两个都包含date和id_number列的DataFrame,想要找出第二个表(df2)中缺失的id_number(即第一个表df1存在,但df2里没有的id),用来做数据对比。以下是我的测试代码:

import pandas as pd

data1 = {'date':  ['7/09/22', '7/09/22', '7/09/22'],
        'second_column': ['first_value', 'second_value', 'third_value'],
         'id_number':['AA576bdk89', 'GG6jabkhd589', 'BXV6jabd589'],
        'fourth_column':['first_value', 'second_value', 'third_value'],
        }

data2 = {'date':  ['7/09/22', '7/09/22', '7/09/22', '7/09/22', '7/09/22', '7/09/22'],
        'second_column': ['first_value', 'second_value', 'third_value','fourth_value', 'fifth_value','sixth_value'],
         'id_number':['AA576bdk89', 'GG6jabkhd589', 'BXV6jabd589','BXV6mkjdd589','GGdbkz589', 'BXhshhsd589'],
        'fourth_column':['first_value', 'second_value', 'third_value','fourth_value', 'fifth_value','sixth_value'],
        }

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

print(df1)
print('\n')
print(df2)

解决方案

方法1:用isin()快速筛选

这是最直接的方法,通过反向匹配找出df1中有但df2没有的id:

# 获取df2中缺失的id对应的整行数据
missing_ids_rows = df1[~df1['id_number'].isin(df2['id_number'])]
print("df2中缺失的id_number对应的行:")
print(missing_ids_rows)

# 如果只需要id_number的列表
missing_id_list = df1[~df1['id_number'].isin(df2['id_number'])]['id_number'].tolist()
print("\ndf2中缺失的id_number列表:")
print(missing_id_list)

方法2:用merge()左连接定位

通过左连接两个表,利用_merge标记找出匹配失败的行,适合需要保留完整数据结构的场景:

# 只保留df2的id_number列做连接,减少计算量
merged_df = df1.merge(df2[['id_number']], on='id_number', how='left', indicator=True)
# 筛选出仅在df1中存在的行
missing_ids_rows = merged_df[merged_df['_merge'] == 'left_only'].drop('_merge', axis=1)
print("df2中缺失的id_number对应的行:")
print(missing_ids_rows)

补充:如果需要找df2新增的id

如果你的实际需求是找出df2有但df1没有的id(也就是df1缺失的id),只需要调换两个表的位置即可:

extra_ids_rows = df2[~df2['id_number'].isin(df1['id_number'])]
print("df2中存在但df1缺失的id_number对应的行:")
print(extra_ids_rows)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:20:37