Skip to content
Advertisement

How to filter out pandas dataframe rows based on contains condition?

I have below dataframe

df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': ['News: Latest', 'News', 'Cricket', 'Football', 'Football Match: India']})
print(df)

   vals                    ids
0     1           News: Latest
1     2                   News
2     3                Cricket
3     4               Football
4     5  Football Match: India

I have input array, by which i wanted to check df and filter out corresponding data.

valueToFilter = ["News", "India"]

Output i want

   vals                    ids
0     1           News: Latest
1     2                   News
2     5  Football Match: India

Can anyone guide me how can i achieve this ?

Advertisement

Answer

You can try this –

>>> import pandas as pd
>>> df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': ['News: Latest', 'News', 'Cricket', 'Football', 'Football Match: India']})
>>> valueToFilter = ["News", "India"]
>>> filter_mask = df['ids'].str.contains('|'.join(valueToFilter))
>>> 
>>> df.loc[filter_mask]
   vals                    ids
0     1           News: Latest
1     2                   News
4     5  Football Match: India

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement