【问题标题】:Dataframe columns have numbers many of them in str format and many in float, how do I convert all of them to float数据框列有许多 str 格式和浮点数,我如何将它们全部转换为浮点数
【发布时间】:2019-12-09 12:54:59
【问题描述】:

我得到了一个带有数值列的数据框,尽管我刚刚意识到其中许多是“str”(其中包含逗号)并且许多是浮点数。这是因为它的多个文件的串联和数据类型不一致。将它们全部转换为浮点数的最佳方法是什么? 我尝试了一些东西

PKupdated['DC'].astype(float) 这给了我这个错误 ValueError: could not convert string to float: '-1,519.97'

尝试替换逗号 PKupdated['DC'].str.replace(',','') 但看起来这正在将我所有的浮点数转换为“NaN”

有什么方法可以将 str 转换为浮点数,而不影响现有的浮点数。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用 apply 区分字符串和浮点数:

    PKupdated['DC'].apply(lambda x: float(x.replace(',', '')) if isinstance(x, str) else x)
    

    【讨论】:

    • 谢谢@mcsoini btw 刚刚意识到它也有“£”(除了逗号)你如何将它添加到你的行中?
    • x.replace(',', '').replace('£', '')
    猜你喜欢
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多