【问题标题】:Regex:: 'pandas._libs.interval.Interval' object has no attribute 'replace'正则表达式:: 'pandas._libs.interval.Interval' 对象没有属性 'replace'
【发布时间】:2021-08-30 13:40:15
【问题描述】:

我有一个带有列的数据框

id       bins                  
1      (2, 3]        
2      (4, 5]       
3      (6, 7]        
4      (8, 9]       
5      (10, 11]      

我正在尝试得到这样的东西。

    id       bins                  
    1      2 -  3        
    2      4 -  5       
    3      6 -  7        
    4      8 -  9       
    5      10 -  11 

我的目标是使用正则表达式来实现这一点。恐怕我不是正则表达式方面的专家。这部分是我尝试但没有成功的解决方案。

   df['bins'].astype(str).str.replace(']', ' ')
   df['bins'].astype(str).str.replace(',', ' - ')
   df['bins'] = df['bins'].apply(lambda x: x.replace('[','').replace(']',''))

任何帮助将不胜感激!

提前致谢

【问题讨论】:

    标签: python regex data-wrangling


    【解决方案1】:

    你可以使用

    df['bins'] = df['bins'].astype(str).str.replace(r'[][()]+', '', regex=True).str.replace(',', ' - ')
    

    注意:

    • .replace(r'[][()]+', '', regex=True) - 删除一个或多个 ][() 字符
    • .str.replace(',', ' - ') - 用空格+-+空格替换所有逗号。

    另一种方式:

    df['bins'].astype(str).str.replace(r'\((\d+)\s*,\s*(\d+)]', r'\1 - \2', regex=True)
    

    这里,\((\d+)\s*,\s*(\d+)] 匹配

    • \( - 一个 ( 字符
    • (\d+) - 第 1 组 (\1):一位或多位数字
    • \s*,\s* - 用零个或多个空格括起来的逗号
    • (\d+) - 第 2 组 (\2):一位或多位数字
    • ] - 一个 ] 字符。

    熊猫测试:

    >>> import pandas as pd
    >>> df = pd.DataFrame({'bins':['(2, 3]']})
    >>> df['bins'].astype(str).str.replace(r'\((\d+)\s*,\s*(\d+)]', r'\1 - \2', regex=True)
    0    2 - 3
    Name: bins, dtype: object
    >>> df['bins'].astype(str).str.replace(r'[][()]+', '', regex=True).str.replace(',', ' - ')
    0    2 -  3
    Name: bins, dtype: object
    

    【讨论】:

      【解决方案2】:

      我会用re 做一些不同的事情。寻找数字并将它们加入一个字符串:

      df['bins'] = df['bins'].apply(lambda x: " - ".join(re.findall("(\d+)", x)))
      
      df
         id     bins 
      0   1    2 - 3
      1   2    4 - 5
      2   3    6 - 7
      3   4    8 - 9 
      4   5  10 - 11 
      

      【讨论】:

        【解决方案3】:

        你做到了

           df['bins'].astype(str).str.replace(']', ' ')
           df['bins'].astype(str).str.replace(',', ' - ')
        

        但是.str.replace 不能在原地工作,你应该分配它返回的东西,否则你的pandas.DataFrame 不会做任何改变,简单的例子:

        import pandas as pd
        df = pd.DataFrame({'col1':[100,200,300]})
        df['col1'].astype(str).str.replace('100','1000')
        print(df)  # there is still 100
        df['col1'] = df['col1'].astype(str).str.replace('100','1000')
        print(df)  # now there is 1000 rather than 100
        

        【讨论】:

          猜你喜欢
          • 2010-12-02
          • 1970-01-01
          • 1970-01-01
          • 2019-06-09
          • 2018-04-19
          • 1970-01-01
          • 1970-01-01
          • 2012-03-18
          • 1970-01-01
          相关资源
          最近更新 更多