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

如何筛选Pandas DataFrame中列表列完全匹配指定列表的行?

筛选Pandas DataFrame中列表列完全匹配指定值的行

问题描述

现有如下结构的Pandas DataFrame:

molecule            species
0        a              [dog]
1        b       [horse, pig]
2        c         [cat, dog]
3        d  [cat, horse, pig]
4        e     [chicken, pig]

需要提取species列**完全等于['dog']**的行(注意不是筛选包含dog元素的行),预期结果如下:

molecule            species
0        a              [dog]

测试代码:

selection = ['dog']
df = pd.DataFrame({
    'molecule': ['a','b','c','d','e'], 
    'species' : [['dog'], ['horse','pig'],['cat', 'dog'], ['cat','horse','pig'], ['chicken','pig']]
})

最简实现方案

直接使用Pandas的元素级比较即可,代码非常简洁:

result = df[df['species'] == selection]
print(result)

执行后将输出符合要求的结果。

如果需要更直观的逻辑表达,也可以用apply方法实现:

result = df[df['species'].apply(lambda x: x == selection)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:20:20