0

I am trying to filter all rows containing two words: mom and dad.

Family
My mom is a teacher. 
My dad is a policeman.
Both my mom and dad are retired. 

My expected output would be

Both my mom and dad are retired

as it contains both the words. I have tried with str.contains(). Just wondering if there is another approach to do it.

s = df.Family
searchfor = ['mom', 'dad']
found = [s.str.contains(x) for x in searchfor]
result = pd.DataFrame[found]
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

1 Answers1

2

Try str.contains with regex (?=.*mom)(?=.*dad), which will match a string that contains both mom and dad (this is done by using two look ahead assertions ?=, i.e. assert the string matches both .*mom and .*dad):

df[df.Family.str.contains(r'(?=.*mom)(?=.*dad)')]
#                               Family
# 2  Both my mom and dad are retired. 

Demo Link

Psidom
  • 209,562
  • 33
  • 339
  • 356