如何筛选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
相关产品推荐
相关产品推荐

