【问题标题】:How to convert multiple columns with european numbers (comma as decimal separator) to float?如何将带有欧洲数字(逗号作为小数分隔符)的多列转换为浮点数?
【发布时间】:2020-10-15 04:51:07
【问题描述】:

我有多个列包含欧洲格式的数字,例如

1.630,78

它们在前面或末尾有不同的字符(€、%),所以我不能使用 pandas 转换器功能。

pd.read_csv("file.csv", decimal=',', separator={"col1": float, "col": float}

不会工作,因为我必须先删除标志,我只能在阅读整个文件后才能做到。

Search and replace dots and commas in pandas dataframe

没用,我得到了一个

ValueError: could not convert string to float: ''

但每一行都有一个条目

如何将特定列中的这些字符串更改为浮点数?

【问题讨论】:

    标签: pandas floating-point numbers digit-separator


    【解决方案1】:

    将列作为字符串读取,然后使用translate

    tt = str.maketrans(',', '.', '.€%')
    df.col1 = df.col1.str.translate(tt).astype(float)
    

    PS:您可能需要采用第三个参数以及需要删除的字符。

    【讨论】:

    • 感谢您的回答。如何将此应用于需要转换的列名列表?
    • 你可以使用循环:for c in my_col_list:df[c] = df[c].str.translate(tt).astype(float)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多