1

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 ?

Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
  • 1
    This should help: [How to test if a string contains one of the substrings in a list, in pandas?](https://stackoverflow.com/questions/26577516/how-to-test-if-a-string-contains-one-of-the-substrings-in-a-list-in-pandas) – bb1 Mar 25 '21 at 04:04

1 Answers1

2

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

Vaebhav
  • 4,672
  • 1
  • 13
  • 33