How to filter Pandas DataFrame by checking whether a Column contains any String from a List?

Question:

Context

I have a Pandas DataFrame and would like to filter it by only including Rows that contain any String from a given List. However, I can’t find a solution in the Pandas Documentation.


Code

DataFrame

ID      Names
0       'NameA NameB'
1       'NameB'
2       'NameB NameC'
3       'NameC'
data: pandas.DataFrame = ...
names = ['NameA', 'NameC']

filteredData = data.filter ... # ?

In this example, when filtering, only the Row with ID = 1 should be removed, since it does not contain one the defined Names.


Question

  • How can I achieve the described goal above?
Asked By: christophriepe

||

Answers:

use:

df2=data.loc[data['Names'].str.contains('|'.join(names))]
Answered By: Clegane

enter image description here

Please be sure to answer the question. Provide details and share your research!

Answered By: G.G
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.