【问题标题】:How to use regex capture groups in pandas replace function如何在熊猫替换功能中使用正则表达式捕获组
【发布时间】:2020-04-08 12:31:21
【问题描述】:

我有一个使用“2Nd”而不是“2nd”、“136Th”而不是“136th”等的 pandas DataFrame。我希望紧跟在数字后面的字母是小写的。

样本数据:

data = pd.Series(['21St StNew York', 'Exampe BlvdSt Louis', '1St Rd'])

期望的输出:

['21st StNew York', 'Exampe BlvdSt Louis', '1st Rd']

尝试使用str.replace()

data = data.str.replace('\BSt', 'st', regex=True)
['21st StNew York', 'Exampe Blvdst Louis', '1st Rd']

是否可以使用捕获组?

data = data.str.replace('[0-9]+(St)', 'st', regex=True)
['st StNew York', 'Exampe BlvdSt Louis', 'st Rd']

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    使用repl的可调用对象

    new_data = data.str.replace('(\d+[A-Z])', lambda m: m.group(1).lower())
    
    Out[49]:
    0        21st StNew York
    1    Exampe BlvdSt Louis
    2                 1st Rd
    dtype: object
    

    【讨论】:

      【解决方案2】:

      我们可以尝试对模式(?<=\d)[A-Z]进行正则表达式替换,然后替换为小写版本:

      df['dat'] = df['data'].str.replace(r'(?<=\d)[A-Z]', lambda x: x.group(0).lower())
      

      【讨论】:

      • 由于某种原因,这会为我返回空值。
      猜你喜欢
      • 2017-05-19
      • 2020-12-28
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多