I have below dataframe
JavaScript
x
10
10
1
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': ['News: Latest', 'News', 'Cricket', 'Football', 'Football Match: India']})
2
print(df)
3
4
vals ids
5
0 1 News: Latest
6
1 2 News
7
2 3 Cricket
8
3 4 Football
9
4 5 Football Match: India
10
I have input array, by which i wanted to check df and filter out corresponding data.
JavaScript
1
2
1
valueToFilter = ["News", "India"]
2
Output i want
JavaScript
1
5
1
vals ids
2
0 1 News: Latest
3
1 2 News
4
2 5 Football Match: India
5
Can anyone guide me how can i achieve this ?
Advertisement
Answer
You can try this –
JavaScript
1
12
12
1
>>> import pandas as pd
2
>>> df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': ['News: Latest', 'News', 'Cricket', 'Football', 'Football Match: India']})
3
>>> valueToFilter = ["News", "India"]
4
>>> filter_mask = df['ids'].str.contains('|'.join(valueToFilter))
5
>>>
6
>>> df.loc[filter_mask]
7
vals ids
8
0 1 News: Latest
9
1 2 News
10
4 5 Football Match: India
11
12