【问题标题】:pandas applying regex to replace valuespandas 应用正则表达式替换值
【发布时间】:2014-04-30 13:33:39
【问题描述】:

我已将一些定价数据读入 pandas 数据框中,这些值显示为:

$40,000*
$40000 conditions attached

我想将其简化为仅数值。 我知道我可以循环并应用正则表达式

[0-9]+

到每个字段,然后将结果列表重新连接在一起,但有没有一种不循环的方式?

谢谢

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    你可以使用Series.str.replace:

    import pandas as pd
    
    df = pd.DataFrame(['$40,000*','$40000 conditions attached'], columns=['P'])
    print(df)
    #                             P
    # 0                    $40,000*
    # 1  $40000 conditions attached
    
    df['P'] = df['P'].str.replace(r'\D+', '', regex=True).astype('int')
    print(df)
    

    产量

           P
    0  40000
    1  40000
    

    因为\D 匹配任何character that is not a decimal digit

    【讨论】:

      【解决方案2】:

      万一有人还在读这篇文章。我正在处理一个类似的问题,需要使用我用 re.sub 找到的正则表达式替换一整列熊猫数据

      要将这个应用到我的整个专栏,这里是代码。

      #add_map is rules of replacement for the strings in pd df.
      add_map = dict([
          ("AV", "Avenue"),
          ("BV", "Boulevard"),
          ("BP", "Bypass"), 
          ("BY", "Bypass"),
          ("CL", "Circle"),
          ("DR", "Drive"),
          ("LA", "Lane"),
          ("PY", "Parkway"),
          ("RD", "Road"),
          ("ST", "Street"),
          ("WY", "Way"),
          ("TR", "Trail"),
          
            
      ])
      
      obj = data_909['Address'].copy() #data_909['Address'] contains the original address'
      for k,v in add_map.items(): #based on the rules in the dict
          rule1 = (r"(\b)(%s)(\b)" % k) #replace the k only if they're alone (lookup \
      b)
          rule2 = (lambda m: add_map.get(m.group(), m.group())) #found this online, no idea wtf this does but it works
          obj = obj.str.replace(rule1, rule2, regex=True, flags=re.IGNORECASE) #use flags here to avoid the dictionary iteration problem
      data_909['Address_n'] = obj #store it! 
      

      希望这可以帮助任何搜索我遇​​到的问题的人。干杯

      【讨论】:

      • rule2 = (lambda... 用作可调用对象,因此在您的obj.str.replace 中,正则表达式被传递匹配对象,即您的字典键以查找要替换的值对。阅读pandas.Series.str.replacedict.get() 了解更多信息。如果有人对m.group() 功能有任何澄清,请告诉我。
      【解决方案3】:

      您可以使用 pandas 的替换方法;您也可能希望保留千位分隔符“,”和小数位分隔符“。”

      import pandas as pd
      
      df = pd.DataFrame(['$40,000.32*','$40000 conditions attached'], columns=['pricing'])
      df['pricing'].replace(to_replace="\$([0-9,\.]+).*", value=r"\1", regex=True, inplace=True)
      print(df)
      pricing
      0  40,000.32
      1      40000
      

      【讨论】:

        【解决方案4】:

        您不需要正则表达式。这应该有效:

        df['col'] = df['col'].astype(str).convert_objects(convert_numeric=True)

        【讨论】:

          【解决方案5】:

          您可以使用re.sub() 删除所有非数字:

          value = re.sub(r"[^0-9]+", "", value)
          

          regex101 demo

          【讨论】:

          • \D+ 将是最小的:-P
          • 将其应用于数据框中的列的最佳方法是什么?所以我有 df['pricing'] 我只是逐行循环吗?
          • 好的,我想我得到它供熊猫使用:df['Pricing'].replace(to_replace='[^0-9]+', value='',inplace==True,regex =True) .replace 方法使用 re.sub
          • 警告 - 去除所有非数字符号将删除负号小数点,并将不相关的数字连接在一起,例如“$8.99 but $2 off with coupon”变成了“8992”,“$5.99”变成了“499”,“$5”变成了“5”。
          • @KillerSnail 您的解决方案需要更正:inplace 后的双等号 (==) 应替换为单等号 (=) df['Pricing'].replace(to_replace='[^0- 9]+', value='',inplace=True,regex=True)
          猜你喜欢
          • 2019-05-31
          • 1970-01-01
          • 2020-01-21
          • 2021-12-07
          • 1970-01-01
          • 1970-01-01
          • 2019-01-24
          相关资源
          最近更新 更多