检查 pandas 列是否包含列表中的所有元素 [英] Check if pandas column contains all elements from a list

查看:106
本文介绍了检查 pandas 列是否包含列表中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 df:

I have a df like this:

frame = pd.DataFrame({'a' : ['a,b,c', 'a,c,f', 'b,d,f','a,z,c']})

还有一个项目列表:

letters = ['a','c']

我的目标是从 frame 中获取至少包含 letters

My goal is to get all the rows from frame that contain at least the 2 elements in letters

我想出了这个解决方案:

I came up with this solution:

for i in letters:
    subframe = frame[frame['a'].str.contains(i)]

这给了我想要的东西,但它可能不是可扩展性方面的最佳解决方案.有没有矢量化"的解决方案?谢谢

This gives me what I want, but it might not be the best solution in terms of scalability. Is there any 'vectorised' solution? Thanks

推荐答案

我会构建一个系列列表,然后应用矢量化的np.all:

I would build a list of Series, and then apply a vectorized np.all:

contains = [frame['a'].str.contains(i) for i in letters]
resul = frame[np.all(contains, axis=0)]

它按预期给出:

       a
0  a,b,c
1  a,c,f
3  a,z,c

这篇关于检查 pandas 列是否包含列表中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆