Skip to content
Advertisement

pandas dataframe str.contains() AND operation

I have a df (Pandas Dataframe) with three rows:

some_col_name
"apple is delicious"
"banana is delicious"
"apple and banana both are delicious"

The function df.col_name.str.contains("apple|banana") will catch all of the rows:

"apple is delicious",
"banana is delicious",
"apple and banana both are delicious".

How do I apply AND operator to the str.contains() method, so that it only grabs strings that contain BOTH “apple” & “banana”?

"apple and banana both are delicious"

I’d like to grab strings that contains 10-20 different words (grape, watermelon, berry, orange, …, etc.)

Advertisement

Answer

You can do that as follows:

df[(df['col_name'].str.contains('apple')) & (df['col_name'].str.contains('banana'))]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement