【问题标题】:Converting percentage string to a float将百分比字符串转换为浮点数
【发布时间】:2022-08-03 07:39:58
【问题描述】:

我一直在努力将百分比字符串转换为浮点数。我尝试了以下代码,但不断收到值或索引错误。在下面找到代码:

census_clean.str.replace(r\'%\', r\'.0\').astype(\'float\') / 100.0

谁能帮忙?如何才能做到这一点?

    标签: pandas


    【解决方案1】:

    样本输入

    df = pd.DataFrame({
        'col' : ["100%", "20%"]
    })
    

    兑换

    df.col.str.replace("%", '').astype(float)
    

    结果

    0    100.0
    1     20.0
    

    【讨论】:

    • 谢谢 srinath,我最终使用了 df.col.astype(str).str.replace('%','').astype(float)/100 并且它起作用了。
    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多