【问题标题】:Getting rid of a specific character in string in Pandas' column摆脱 Pandas 列中字符串中的特定字符
【发布时间】:2020-07-24 00:20:37
【问题描述】:

我正在处理一个包含价格列的大型数据集(超过 200 万行 x 10 列)。这些值的格式包括千点分隔符(例如 1.000),并且还使用点来分隔小数(例如 3.000.75 而不是 3000,75)。

我想将列格式化为浮点数,但值中的那两个点让我很头疼。

通常,为了简单起见,假设没有超过 1.000.000 的数字,我会做这样的事情

for i in range (0,len(df)):
    cell=str(df.iloc[i]['price'])
    if cell.count(".")==2:
        cell=cell.split(".")[0] + cell.split(".")[1] + '.' + cell.split(".")[2]

然后是的,将列格式化为浮点数。

但我知道这远非最佳(for 循环)。

如何使用 pandas 的力量来避免这里出现for

谢谢!

【问题讨论】:

    标签: python pandas for-loop if-statement


    【解决方案1】:

    你可以试试这样的:

    df.price.str.replace(r'(\.)([0-9]{1,2})$', ',\\2')
    

    也许您将不得不使用正则表达式部分,但此功能是一种可行的方法。

    【讨论】:

      【解决方案2】:

      按照 minho 的建议,使用正则表达式删除它们。编码和阅读的一种简单方法是使用\D,这意味着所有非数字字符:

      regex = r'\D'
      df.price = df.price.str.replace(regex, '').astype(float)
      

      【讨论】:

        【解决方案3】:

        在您的情况下,对点存在疑问,即何时删除点以及何时应将点视为小数点。我对这个问题的解决方案是删除所有点,然后在一千之后出现,并保持小数点不变。以下代码可能会对您有所帮助。

        cell = df['price']
        cell = cell.astype('str')
        
        def func(val):
            ret = ''
            for i in range(len(val)):
                if val[i] != '.' or i%4 != 0:
                    ret += val[i]       
        
            return ret
        
        output = pd.Series(map(func,cell))
        
        output = output.astype('float')
        print(output)
        

        如果您遇到任何其他问题,可以给我写信。

        【讨论】:

          猜你喜欢
          • 2022-01-16
          • 1970-01-01
          • 2020-11-14
          • 2011-04-22
          • 2020-04-02
          • 2014-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多