【问题标题】:Replace a string containing parentheses with a float in pandas用 pandas 中的浮点数替换包含括号的字符串
【发布时间】:2020-04-13 01:07:12
【问题描述】:

我有一个包含一列字符串的数据集,我想将其转换为浮点数。但是,该列有一个条目,其中包含括号内的数字(这意味着是负数)。我尝试了不同的方法——间接的和直接的——将值替换为可以让我将其转换为浮点数的表示,但我一直失败,我不明白为什么:

这是括号下的数字为字符串的行:

我的代码:

mask1 = purchases.Amount.str.contains('\(').fillna(False)

purchases.loc[mask1, :]['Amount'] = purchases.loc[mask1, :]['Amount'].str.replace('\(', '-').str.replace('\)', '')

purchases.loc[mask2, :]['Amount'] = purchases.loc[mask2, :]['Amount'].str.replace('\s+', '').str.replace('[a-z]+', '') 

# Both fail to replace

purchases.loc[mask1, :]['Amount'] = '-29.99'  # direct assignment also fails

结果:

我做错了什么?我该如何纠正?

【问题讨论】:

    标签: regex python-3.x pandas replace


    【解决方案1】:

    你可以试试:

    df = pd.DataFrame({'Amount': ['(29.29)', '29.29']})
    print(df)
    
    df['Amount']=df.Amount.apply(lambda x: -float(x[1:-1]) if x[0] == '(' else float(x))
    print(df)
    print(df.dtypes)
    

    结果:

        Amount
    0  (29.29)
    1    29.29
    
       Amount
    0  -29.29
    1   29.29
    
    Amount    float64
    dtype: object
    

    【讨论】:

      【解决方案2】:

      为什么不只检查字符串是否被括号包围,如果是,就去掉它们。

      from decimal import Decimal
      
      def get_amount(s):
          if s[0] == '(' and s[-1] == ')':
              return Decimal(s[1:-1])
          else:
              return Decimal(s)
      

      【讨论】:

        【解决方案3】:

        使用rstrip 删除最后一个),然后替换( 并最后转换为浮点数:

        df = pd.DataFrame({'Amount': ['(29.29)', '(39.39)', '12.5', '340']})
        df['Amount'] = df['Amount'].str.strip(')').str.replace('\(', '-').astype(float)
        print (df)
           Amount
        0  -29.29
        1  -39.39
        2   12.50
        3  340.00
        

        您的解决方案非常接近,您需要什么,只使用 loc 和列 namef 以避免 chain indexing

        mask1 = purchases.Amount.str.contains('\(').fillna(False)
        
        purchases.loc[mask1, 'Amount'] = purchases.loc[mask1, 'Amount'].str.replace('\(', '-').str.replace('\)', '')
        
        purchases.loc[mask2, 'Amount'] = purchases.loc[mask2, 'Amount'].str.replace('\s+', '').str.replace('[a-z]+', '') 
        

        purchases.loc[mask1, 'Amount'] = '-29.99' 
        

        【讨论】:

          猜你喜欢
          • 2017-08-04
          • 2021-03-05
          • 1970-01-01
          • 1970-01-01
          • 2021-12-01
          • 2020-06-12
          • 2019-05-25
          • 2020-07-26
          • 2015-04-16
          相关资源
          最近更新 更多