Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 760
Jan Klaas Avatar asked Jan 05 '23 09:01

Jan Klaas


1 Answers

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]
like image 119
Psidom Avatar answered Jan 13 '23 10:01

Psidom