python - 当字符串以 .(dot) 和边界线结尾时,Pandas str.contains 不给出有效结果
问题描述
我最后有一个列值.
say New York .
。当我尝试使用边界线 ( ) 搜索相同的内容时,\b
它会给出无效的结果。
请在下面找到代码片段。
# importing pandas as pd
import pandas as pd
# importing re for regular expressions
import re
# Creating the Series
sr = pd.Series(['The New York . City'])
# Creating the index
idx = ['City 1']
# set the index
sr.index = idx
# Print the series
print(sr)
# find if 'is' substring is present
result = sr.str.contains(pat = '\\bNew York \\.\\b')
# print the result
print(result)
预期结果:
City 1 The New York . City
dtype: object
City 1 True
实际结果:
City 1 The New York . City
dtype: object
City 1 False
dtype: bool
解决方案
利用
result = sr.str.contains(pat = '\\bNew York \\.')
没有最后\\b
。正如文档所述:
\b
Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that
形式上,\b 被定义为 \w 和 \W 字符之间的边界(反之亦然),或 \w 和字符串的开头/结尾之间的边界。
由于句点不是单词字符,因此\\b
在句点之后使用将不匹配。如果您需要确保单点后有空格,请添加 a\\s
代替。
为了您的理智,请使用原始字符串,这样可以避免双重转义:
result = sr.str.contains(pat = r'\bNew York \.')
(注意r
字符串前面的前缀。同样,请参阅文档。)
推荐阅读
- azure - 如何在远程 Azure VM 上执行 Powershell 命令/脚本?
- excel - 动态条件格式(索引、匹配)
- android - 在 RecyclerView 中预取文本布局,无法解析方法 setTextFuture
- python - sqlite 如果存在则更新,否则在 python 中插入
- android - 比较 Firebase Auth 和 Firebase Object 中的属性
- php - 在 Woocommerce Checkout 上删除某个国家/地区的特定州
- node.js - /token 请求中的 404 响应
- azure - Azure 自动化在返回 400 错误的混合工作人员上调用内部应用程序 Rest API
- wordpress - WP Bakery Visual Composer 无法使用 WP 5.0
- crystal-reports - 在主报表 Crystal Reports 中使用子报表数据