基于指定列对比两个DataFrame,返回另一DataFrame中不存在的行——以cust_id列对比df1与df2为例
筛选df2中cust_id不在df1里的行
嘿,我来帮你搞定这个需求!这里有两种实用的方法可以实现你的目标,直接看代码和解释吧:
第一步:先构造示例数据
首先我们先把你给出的df1和df2用pandas构造出来,方便后续测试:
import pandas as pd # 构造df1 df1 = pd.DataFrame({ 'name': ['cxa', 'cxb', 'cxc', 'cxd'], 'cust_id': ['c1001', 'c1002', 'c1003', 'c1004'] }) # 构造df2 df2 = pd.DataFrame({ 'name': ['cxa', 'cxb', 'cxc', 'cxd', 'cxe', 'cxf'], 'cust_id': ['c1001', 'c1002', 'c1003', 'c1004', 'c1005', 'c1006'], 'qty': [10, 20, 10, 15, 20, 20] })
方法一:用isin()+取反(最直观)
这是最简单直接的方式,先拿到df1的所有cust_id,再筛选df2中不在这个列表里的行:
# 获取df1的cust_id集合 df1_custs = df1['cust_id'] # 筛选目标行:~表示取反,即"不在列表里" result = df2[~df2['cust_id'].isin(df1_custs)] print(result)
方法二:用merge()左连接(适合复杂关联场景)
如果后续需要更复杂的表关联操作,这种方法扩展性更好:
# 左连接两个表,只关联cust_id列,添加_merge标记列 merged = df2.merge(df1[['cust_id']], on='cust_id', how='left', indicator=True) # 筛选出只有df2存在的行,然后删掉标记列 result = merged[merged['_merge'] == 'left_only'].drop('_merge', axis=1) print(result)
最终输出结果
两种方法运行后都会得到你想要的结果:
name cust_id qty 4 cxe c1005 20 5 cxf c1006 20
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

