【问题标题】:How do I convert DataFrame column of type "string" to "float" using .replace?如何使用 .replace 将“string”类型的 DataFrame 列转换为“float”?
【发布时间】:2021-11-09 16:54:50
【问题描述】:

在我的 DataFrame 中,“Value_String”列由以下字符串组成:

  • 类似数字的字符串,以美元符号开头,千位用逗号分隔,[e.g. $1,000]
  • “无”

因此,我尝试创建一个新列并使用以下 lambda 函数将字符串转换为浮点数:

to_replace = '$,'

df['Value_Float'] = df[df['Value_String'].apply(lambda x: 0 if x == 'None' 
else float(x.replace(y, '')) for y in to_replace)]

这实际上会生成一个“TypeError: 'generator' object is not callable”。

我该如何解决这个问题?

【问题讨论】:

    标签: python string type-conversion


    【解决方案1】:

    numpy where 方法对于有条件地更新值非常有帮助。在这种情况下,值不是“无”,我们将使用替换功能。但是由于str.replace 默认使用正则表达式,我们需要将模式更改为文字美元符号或逗号

    import pandas as pd
    import numpy as np
    df = pd.DataFrame({'Value_String':["$1,000","None"]})
    df['Value_String'] = np.where(df['Value_String']!='None', df['Value_String'].str.replace('\$|,',''), df['Value_String'])
    print(df)
    

    输出

      Value_String
    0         1000
    1         None
    

    【讨论】:

    • 谢谢你,np.where 方法确实可以完成这项工作。同时。我再次尝试使用 lambda 函数,它确实有效。对于我最初的问题,我仍然希望将所有字符替换为一个字符串,对此有什么建议吗? df_'Value_Float'] = df[Value'_String].apply(lambda x: 0 if x == 'None' else float(x.replace('$', '').replace(',', '') ))
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 2014-10-06
    • 2019-06-22
    • 2015-11-05
    • 1970-01-01
    • 2019-12-11
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多