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

Search of a set of strings in a column containing strings in a pandas dataframe

I have a df with multiple columns, one of which is a string with many words(text column).

I also have a set of words, S, that I need to look for.

I want to extract the rows of the df that contain at least one word from S in its text column

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

df_filtered=df[df['text'].str.contains('word')]

This works for one word from the set S. Instead of looping over S, is there a better way?

>Solution :

If you want to match full words, use:

import re

pattern = '|'.join(map(re.escape, S))

df_filtered = df[df['text'].str.contains(fr'\b(?:{pattern})\b')]
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