【问题标题】:Strict regex in Pandas replacePandas 中的严格正则表达式替换
【发布时间】: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


【解决方案1】:

\bword boundaries 添加到dict 的每个键:

d = {'UK': 'United Kingdom', 'LA': 'Los Angeles', 'NYC': 'New York City', 'NY' : 'New York'}

data = {'Categories': ['animal','plant','object'],
    'Type': ['tree','dog','rock'],
        'Comment': ['The NYC tree is very big', 'NY The cat from the UK is small',
                    'The rock was found in LA.']
}

d = {r'\b' + k + r'\b':v for k, v in d.items()}

df = pd.DataFrame(data)

df['commentTest'] = df['Comment'].replace(d, regex=True)
print (df)
  Categories                          Comment  Type  \
0     animal         The NYC tree is very big  tree   
1      plant  NY The cat from the UK is small   dog   
2     object        The rock was found in LA.  rock   

                                         commentTest  
0                 The New York City tree is very big  
1  New York The cat from the United Kingdom is small  
2                 The rock was found in Los Angeles.  

【讨论】:

    猜你喜欢
    • 2014-04-30
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多