为什么Pandas series.str.contains方法在有前导空格的情况下检测不到匹配



我想查找包含字符串' (target)'的所有索引值。

示例:

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

我得到的:

[False False False]

我所期望的:

[ True False False]

比较:

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

生产:

[ True False False]
[ True False False]
事实证明,regex参数的默认设置是True
  • 使用regex,(...)意味着捕获里面的所有内容,所以它试图找到' target'而不是' (target)'
  • 解决此问题的选项包括:
    • 设置regex=False
    • (...)转义括号

因此,要获得所需的行为,有两个选项:

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

传递regexFalse,()这里是regex样式的

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

最新更新