I have a df (Pandas Dataframe) with three rows:
JavaScript
x
5
1
some_col_name
2
"apple is delicious"
3
"banana is delicious"
4
"apple and banana both are delicious"
5
The function df.col_name.str.contains("apple|banana")
will catch all of the rows:
JavaScript
1
4
1
"apple is delicious",
2
"banana is delicious",
3
"apple and banana both are delicious".
4
How do I apply AND operator to the str.contains()
method, so that it only grabs strings that contain BOTH “apple” & “banana”?
JavaScript
1
2
1
"apple and banana both are delicious"
2
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:
JavaScript
1
2
1
df[(df['col_name'].str.contains('apple')) & (df['col_name'].str.contains('banana'))]
2