[英]How to filter out pandas dataframe rows based on contains condition?
I have below dataframe我有以下 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.我有输入数组,我想通过它检查 df 并过滤掉相应的数据。
valueToFilter = ["News", "India"]
Output i want Output 我想要
vals ids
0 1 News: Latest
1 2 News
2 5 Football Match: India
Can anyone guide me how can i achieve this?谁能指导我如何实现这一目标?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.