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

能否在Pandas中结合多个.isin()方法过滤DataFrame?

在Pandas中结合多个.isin()方法过滤DataFrame

示例数据

df1:

co | no  | ds
A1 | yes | text1
A2 | no  | text1
A3 | no  | text3

df2:

co | no  | ds
A1 | yes | text1
A5 | no  | text5
A6 | yes | text6

需求

筛选出整行数据完全存在于另一个DataFrame中的行。

修正你的写法

你尝试的代码有语法错误,df1[df1['co'].isin(df2['co'])]返回的是过滤后的DataFrame,不能直接和另一个DataFrame用&运算。正确的做法是先给每一列生成布尔值序列,再按行做逻辑与:

# 生成各列的匹配条件
cond_co = df1['co'].isin(df2['co'])
cond_no = df1['no'].isin(df2['no'])
cond_ds = df1['ds'].isin(df2['ds'])

# 组合条件并过滤
df1 = df1[cond_co & cond_no & cond_ds]

执行后得到预期结果:

co | no  | ds
A1 | yes | text1

更精准的整行匹配(推荐)

上面的方式可能出现“各列分别在df2中存在,但组合起来的行其实不在df2”的情况。如果要严格筛选整行完全存在于df2的记录,可以把每行转为元组,再判断是否在df2的行元组集合里:

# 把df2的所有行转为元组并存入集合
df2_row_set = set(df2.itertuples(index=False, name=None))

# 过滤df1中存在于该集合的行
df1 = df1[df1.itertuples(index=False, name=None).isin(df2_row_set)]

这种方式能确保筛选出的行是df2中实实在在存在的完整行,结果和预期一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:20:28