事实证明,
我想查找包含字符串' (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)')
传递regex
False,()
这里是regex样式的
index.str.contains(' (target)',regex=False)
Out[103]: array([ True, False, False])