Check if Python list elements are in a Pandas dataframe row

Viewed 2148

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

4 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.

Similar question has been asked before. link to that question

import pandas as pd

df = pd.DataFrame({'Color':['Blue', 'Green', 'Yellow', 'Purple','Orange'], 
    'Number':[20, 21, 19, 18, 40],
    'Code':['ss', 'dd', 'ee', 'xx', 'tt'],
    'Flag':[1, 1, 0, 1, 0]
})

names = set(['Yellow', 0, 'ee'])

m = [names.issubset(i) for i in df.values.tolist()]

print(df[m])

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

Image of code

import pandas as pd
data={'Color': ['Blue','Green','Yellow','Purple','Orange'],
      'Number':[20,21,19,18,40],
      'Code':['ss','dd','dd','xx','tt'],
      'Flag':[1,1,0,1,0]}
df=pd.DataFrame(data)
print(df)
my_list=list(df.iloc[2])
print(my_list)

Output of code

Related