簡體   English   中英

為什么 Pandas series.str.contains 方法在有前導空格時檢測不到匹配?

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

我想查找包含字符串' (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

  • 使用正則表達式, (...)表示捕獲內部的所有內容,因此它試圖找到' 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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM