【发布时间】:2018-03-02 21:59:27
【问题描述】:
我需要编写一个严格的regular expression 来替换我的pandas 数据框中的某些值。这是在解决我发布的here 的问题后提出的问题。
问题在于.replace(idsToReplace, regex=True) 并不严格。因此,如果 iDsToReplace 是:
NY : New York
NYC : New York City
我们替换 ID 的注释是:
My cat from NYC is large.
得到的响应是:
My cat from New York is large.
pandasreplace 函数中是否有一种 Python 方法可以使 regular expression 更严格地匹配 NYC 而不是 NY?
【问题讨论】:
-
正则表达式中没有严格的概念,它只是匹配你告诉它的内容。您可能正在寻找
\b字边界。 -
对不起,如果dict是
d = {'NYC': 'New York City', 'NY' : 'New York'},是否需要将My cat from NYC is large.替换为My cat from New York City is large.? -
问题是单词 NYC 被 NY 捕获,而不是 NYC。因此,正确答案是:“我来自纽约市的猫很大”。我正在做一些测试,但到目前为止,您的以下答案似乎正在使用
bounds -
@owwoow14 - 超级,很高兴能帮上忙!
标签: regex python-2.7 pandas replace