【问题标题】:Python pandas regular expression replace part of the matching patternPython pandas 正则表达式替换部分匹配模式
【发布时间】:2015-10-17 08:14:21
【问题描述】:

我有一堆这样的地址:

df['street'] =
    5311 Whitsett Ave 34
    355 Sawyer St
    607 Hampshire Rd #358
    342 Old Hwy 1
    267 W Juniper Dr 402

我想要做的是删除地址的街道部分末尾的那些数字:

df['street'] =
    5311 Whitsett Ave
    355 Sawyer St
    607 Hampshire Rd
    342 Old Hwy 1
    267 W Juniper Dr

我的正则表达式是这样的:

df['street'] = df.street.str.replace(r"""\s(?:dr|ave|rd)[^a-zA-Z]\D*\d+$""", '', case=False)

这给了我这个:

df['street'] =
    5311 Whitsett
    355 Sawyer St
    607 Hampshire
    342 Old Hwy 1
    267 W Juniper

它从我原来的街道地址中删除了“Ave”、“Rd”和“Dr”这几个词。有没有办法保留正则表达式模式的一部分(在我的情况下,这是 'Ave'、'Rd'、'Dr' 并替换其余部分?

编辑: 注意地址342 Old Hwy 1。我不想在这种情况下也取出号码。这就是为什么我指定模式(“Ave”、“Rd”、“Dr”等)以更好地控制谁被更改。

【问题讨论】:

  • 就用这个r"\s*#?\d+$"正则表达式
  • @AvinashRaj 对不起,我不明白你提出的建议。能详细点吗?
  • 试试uu.street.str.replace(r"\s*#?\d+$", '', case=False)
  • 在默认python中,我应该使用re.sub(regex, replace, string)
  • 对不起,我不明白您建议的模式如何适合我的情况。我得到 \s* 匹配 0 个或更多空格,不确定“#”是什么?意思是,那么 \d+$ 是我的结束条件。

标签: python regex pandas


【解决方案1】:
    df_street = '''
        5311 Whitsett Ave 34
        355 Sawyer St
        607 Hampshire Rd #358
        342 Old Hwy 1
        267 W Juniper Dr 402
        '''
    # digits on the end are preceded by one of ( Ave, Rd, Dr), space,
    # may be preceded by a #, and followed by a possible space, and by the newline
   df_street = re.sub(r'(Ave|Rd|Dr)\s+#?\d+\s*\n',r'\1\n', df_street,re.MULTILINE|re.IGNORECASE)
print(df_street)

    5311 Whitsett Ave
    355 Sawyer St
    607 Hampshire Rd
    342 Old Hwy 1
    267 W Juniper Dr

【讨论】:

  • 您的解决方案也不保留“Ave”、“Rd”或“Dr”。我想保留它们。
  • 太完美了。 \1 就是我要找的东西!
【解决方案2】:

您应该使用以下正则表达式:

>>> import re
>>> example_str = "607 Hampshire Rd #358"
>>> re.sub(r"\s*\#?[^\D]+\s*$", r"", example_str)
'607 Hampshire Rd'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2012-05-16
    • 2011-05-28
    • 1970-01-01
    • 2014-05-12
    • 2022-08-10
    相关资源
    最近更新 更多