Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

use:

df2=data.loc[data['Names'].str.contains('|'.join(names))]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading