Jan Klaas
Jan Klaas

Reputation: 371

Check whether a string is contained in a element (list) in Pandas

I've got a pandas dataframe with the column 'Friends'. All elements in the column friends are list object. Example of a row in the column 'friends':

['erik', 'jason', 'eduard']

I want to return a dataframe in which I check whether eduard is the list. This is my example code:

df[df.friends.isin(['eduard'])

Help a cat out please

Upvotes: 6

Views: 4631

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210982

You can use sets intersection:

In [66]: df
Out[66]:
                 friends
0  [erik, jason, eduard]
1            [anna, max]
2       [eduard, natali]

In [67]: df[df.friends.map(set) & {'anna','natali'}]
Out[67]:
            friends
1       [anna, max]
2  [eduard, natali]

Upvotes: 2

akuiper
akuiper

Reputation: 215127

You need apply in this case, use the normal in operator to check if list contains eduard:

df[df.friends.apply(lambda x: 'eduard' in x)]

Example:

df = pd.DataFrame({"friends": [['erik', 'jason', 'eduard'], ['erik', 'jason']]})

df[df.friends.apply(lambda x: 'eduard' in x)]
#                 friends
#0  [erik, jason, eduard]

Upvotes: 9

Related Questions