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

如何在Pandas中对DataFrame按col1左连接且按col2反连接?

解决方案

你要实现的逻辑可拆解为:从df2中筛选出col1存在于df1的col1列表中,且**(col1, col2)组合未在df1中出现过**的行。以下是两种简洁的实现方式:

方法一:通过索引匹配筛选

import pandas as pd

# 初始化原始数据
df1 = pd.DataFrame(data = {'col1' : ['finance',  'accounting'], 'col2' : ['f1', 'a1']}) 
df2 = pd.DataFrame(data = {'col1' : ['finance', 'finance', 'finance', 'accounting', 'accounting','IT','IT'], 'col2' : ['f1','f2','f3','a1','a2','I1','I2']})

# 筛选逻辑:
# 1. 保留df2中col1在df1的col1范围内的行
# 2. 排除掉df2中与df1(col1, col2)完全匹配的行
result = df2[
    df2['col1'].isin(df1['col1']) & 
    ~df2.set_index(['col1', 'col2']).index.isin(df1.set_index(['col1', 'col2']).index)
].reset_index(drop=True)

print(result)

输出结果:

col1 col2
0     finance   f2
1     finance   f3
2  accounting   a2

方法二:利用merge的indicator参数

import pandas as pd

# 初始化原始数据
df1 = pd.DataFrame(data = {'col1' : ['finance',  'accounting'], 'col2' : ['f1', 'a1']}) 
df2 = pd.DataFrame(data = {'col1' : ['finance', 'finance', 'finance', 'accounting', 'accounting','IT','IT'], 'col2' : ['f1','f2','f3','a1','a2','I1','I2']})

# 左连接df2和df1,添加匹配标记列
merged = df2.merge(df1, on=['col1', 'col2'], how='left', indicator=True)

# 筛选出:仅在df2中存在的行(left_only),且col1属于df1的col1范围
result = merged[
    (merged['_merge'] == 'left_only') & 
    (merged['col1'].isin(df1['col1']))
].drop(columns='_merge').reset_index(drop=True)

print(result)

输出结果与方法一完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:36:33