Pandas check if splitted dataframe's field contains value

Viewed 82

I have a following dataframe

Name Hobby
Tom  Food,Sport,Art,Extreme Sport
Mark Sport  
John Coding,Books

I want to get all rows, where a person's hobby is for example Sport. I tried to convert field to array by split method but then I can't figure out how to check if pandas array includes specified hobby.

1 Answers

You can use .str.contains() to check the existence of a word in a string.

df[df['Hobby'].str.contains('Sport')]

EDIT:

We need to split the hobbies, so we can have a new dataframe with a line per person per hobby.

Then we can safely filter on the hobby.

SEARCHED_HOBBY = 'Sport'

df = pd.DataFrame({'Name': ['Tom', 'Mark', 'John'], 'Hobby': ['Food,Sport,Art,Extreme Sport','Sport', 'Coding,Books']})

df['Hobby'] = df['Hobby'].str.split(',')

splitted_hobbies = df.explode('Hobby')
splitted_hobbies = splitted_hobbies[splitted_hobbies['Hobby'] == SEARCHED_HOBBY]

df = df[df['Name'].isin(splitted_hobbies['Name'])]
Related