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

如何用Pandas匹配df2的值筛选df1中符合条件的整行数据

解决方法:筛选DataFrame中任意列匹配指定值的行

没问题,这需求很常见,我给你两种实用的实现方式,都能精准得到你想要的df3:

先准备测试数据(方便你复现)

首先我们先把题目里的df1和df2构造出来,确保代码能直接运行:

import pandas as pd

df1 = pd.DataFrame({
    'col1': [55, 12, 18, 52, 15, 16, 17, 31],
    'col2': [66, 25, 22, 15, 30, 17, 30, 20]
})

df2 = pd.DataFrame({'duplicates': [15, 17]})

方法一:用isin() + any(axis=1)(最简洁通用)

这种方法不需要指定具体列,不管df1有多少列都能自动检查每行是否有匹配值,非常省心:

# 先把df2里需要匹配的值提取成列表
match_values = df2['duplicates'].tolist()

# 筛选:每行任意一列包含匹配值的话就保留
df3 = df1[df1.isin(match_values).any(axis=1)]

运行后得到的df3就是你要的结果:

col1  col2
3    52    15
4    15    30
5    16    17
6    17    30

方法二:用query()(直观易懂)

如果你喜欢更直观的查询语句,可以用query动态生成条件,适合列数不多的场景:

match_values = df2['duplicates'].tolist()
# 生成查询条件,比如"col1 in [15,17] or col2 in [15,17]"
query_condition = ' or '.join([f'{col} in @match_values' for col in df1.columns])

df3 = df1.query(query_condition)

这个方法得到的结果和上面完全一致,优势是条件清晰,能直接看到筛选逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:26:58