【问题标题】:Pandas - Remove strings from a float number in a columnPandas - 从列中的浮点数中删除字符串
【发布时间】:2018-06-27 10:14:15
【问题描述】:

我有一个如下的数据框:

plan type  hour status     code
A    cont   0    ok       010.0
A    cont   2    ok      025GWA
A    cont   0    notok   010VVT
A    cont   0    other     6.05
A    vend   1    ok        6.01

列代码有几个不同字母的字符串字符。最后,我想将“代码”列转换为浮动。 我试过了:

df['code'] = df['code'].str.extract('(\d+)').astype(float)

但是我得到了:

plan type  hour status     code
A    cont   0    ok        10.0
A    cont   2    ok        25.0 
A    cont   0    notok     10.0
A    cont   0    other      6.0
A    vend   1    ok         6.0

我怎样才能得到如下结果?

plan type  hour status     code
A    cont   0    ok       10.00
A    cont   2    ok       25.00
A    cont   0    notok    10.00
A    cont   0    other     6.05
A    vend   1    ok        6.01

【问题讨论】:

    标签: python pandas data-cleaning


    【解决方案1】:

    使用(\d*\.?\d*)

    In [441]: df['code'].str.extract('(\d*\.?\d*)', expand=False).astype(float)
    Out[441]:
    0    10.00
    1    25.00
    2    10.00
    3     6.05
    4     6.01
    Name: code, dtype: float64
    

    【讨论】:

    • 我遇到了同样的问题,因为我在一些花车的末尾有%,但它似乎没有删除它。
    【解决方案2】:

    您可以考虑基于替代的方法,而不是提取。

    使用str.replace,然后通过astype/to_numeric 转换转换为浮点数。

     df.code.str.replace('[^\d.]', '').astype(float)
    

    或者,

    pd.to_numeric(df.code.str.replace('[^\d.]', ''), errors='coerce')
    

    0    10.00
    1    25.00
    2    10.00
    3     6.05
    4     6.01
    Name: code, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2021-09-21
      • 1970-01-01
      • 2017-09-18
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      • 2021-12-28
      相关资源
      最近更新 更多