Why does Pandas series.str.contains method not detect match when there is a leading space?

Viewed 624

I want to find all index values that contain the string ' (target)'.

Example:

index = pd.Index(['TIC7201-PV (target)', 'TIC7202-PV', 'TIC7203-PV'])
print(index.str.contains(' (target)'))

What I get:

[False False False]

What I expected:

[ True False False]

For comparison:

print(index.str.contains('(target)'))
print(index.str.endswith(' (target)'))

produces:

[ True False False]
[ True False False]
2 Answers

Turns out, the default setting for the regex argument, is True.

  • With regex, (...) means capture everything inside, so it's trying to find ' target' instead of ' (target)'
  • The options to resolve the issue are:
    • Set regex=False
    • Escape the parenthesis with \(...\)

Therefore, to get the desired behavior, there are two options:

# 1
index.str.contains(' (target)',regex=False)

# 2
index.str.contains(r' \(target\)')

Pass regex False , () here is regex style

index.str.contains(' (target)',regex=False)
Out[103]: array([ True, False, False])
Related