简体   繁体   English

熊猫:检查A列中的值是否在B列中的值列表中的有效方法

[英]Pandas: Efficient way to check if a value in column A is in a list of values in column B

my initial dataframe looks like this 我的初始数据框看起来像这样

 A   | B
-----------------
 'a' | ['1', 'a', 'b']        
 '1' | ['2', '5', '6']   
 'd' | ['a', 'b', 'd']        
 'y' | ['x', '1', 'y']

and I want to check if 'a' is in the corresponding list in B: ['1', 'a', 'b'] 我想检查“ a”是否在B中的相应列表中:['1','a','b']

I could do that by using the apply 我可以通过应用

df.apply(lambda row: row[['A']][0] in row[['B']][0], axis=1)           

that gives me the expected result: 这给了我预期的结果:

[True, False, True, True]

but on the real data I have (millions of rows) that is very heavy and takes ages. 但根据我的实际数据(数百万行)而言,数据非常繁重且需要一定时间。 Is there a more efficient way to do the same thing? 有没有更有效的方法来做同样的事情? for example using numpy elementwise operations or anything else? 例如使用numpy elementwise操作还是其他?

If you convert each column to sets, you can use < to compare pairwise subsets 如果将每列转换为集合,则可以使用<比较成对子集

a = d.A.apply(lambda x: set([x]))
b = d.B.apply(set)

a < b

0     True
1    False
2     True
3     True
dtype: bool

Otherwise, you can use a list comprehension with zip 否则,您可以将列表理解与zip

[a in b for a, b in zip(d.A.values.tolist(), d.B.values.tolist())]

[True, False, True, True]

timing small data 定时小数据

在此处输入图片说明

timing large data 定时大数据

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM