首页 > 解决方案 > 当字符串以 .(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

标签: pythonpandas

解决方案


利用

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字符串前面的前缀。同样,请参阅文档。)


推荐阅读