Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Python list elements are in a Pandas dataframe row

My question might be easy but I can't find the solution quickly. I have a dataframe 'df' and I want to check if elements in my list 'list' exist in any row of df.

This is a df example:

enter image description here

And this is my_list example:

enter image description here

In this case, I want to get row 2 of df as all elements in my_list exist in that row.

Thanks

like image 763
pnna Avatar asked Jul 05 '26 07:07

pnna


2 Answers

You can try pandas isin

df.loc[df.isin(my_list).astype(int).sum(axis=1) == len(my_list), :]

where my_list being your list of searches you want to perform.

NOTE: In case you want a partial match you can play around with the condition.

like image 72
Mahendra Singh Avatar answered Jul 10 '26 13:07

Mahendra Singh


Here's another way using applymap:

df.loc[df.applymap(lambda x: x in names).sum(1).eq(len(names))]

    Color  Number Code  Flag
2  Yellow      19   ee     0
like image 22
YOLO Avatar answered Jul 10 '26 12:07

YOLO