Find row with exact matching with the string i wanted using CONTAINS

Question:

I have a dataframe below, I wanted to find all name contain ‘And’

df = pd.DataFrame({"name": ["Andrew", "Jen And Jess"," Gin And]})

my code
df[df["name"].str.contains('AND',na=False)]

My code’s output included with substring and consist ‘And’

What i expecting:

name
Jen And Jess
Gin And
Asked By: Jyc

||

Answers:

use regex in the contain and surround the ‘And’ with the b (word boundaries)
you can use IGNORECASE flag, to keep the pattern simple

import re

df[df.name.str.contains(r'bandb', flags=re.IGNORECASE , regex=True)]
name
1   Jen And Jess
2   Gin And
Answered By: Naveed

To catch upper and lower, you can do:

import re
df[df["name"].str.contains(r'b[Aa][Nn][Dd]b')]
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.