【问题标题】:how to convert str to float in pandas dataframe如何在熊猫数据框中将str转换为float
【发布时间】:2016-05-28 19:54:54
【问题描述】:

我正在使用下面的行来读取一个 csv 文件,其中 B 列以 str 格式结束,我无法直接将其转换为浮点数:

   df = pd.read_csv('data.csv', sep=";", encoding = "ISO-8859-1")

这会生成一个数据框,其中所有列都是 str 格式:

          A       B
    0   Emma     -20,50
    1   Filo     -15,75
    2   Theo      17,23

您可能会注意到小数点用“,”而不是“.”分隔因为它是德国的csv。 我已经尝试了以下方法(无济于事):

  ..., dtype={'B': np.float32}, decimal= ',' , ....

知道如何在阅读过程中完成它吗?

阅读 csv 后进行修改是有效的(但这是我想避免的低效附加步骤),这就是我使用的:

 df['B'] = df['B'].str.replace(',', '.').astype(float)

【问题讨论】:

    标签: python csv pandas typeconverter


    【解决方案1】:

    对我来说效果很好,我只省略了dtype={'B': np.float32}

    import pandas as pd
    import io
    
    temp=u"""A;B
    0;Emma;-20,50
    1;Filo;-15,75
    2;Theo;17,23"""
    #after testing replace io.StringIO(temp) to filename
    df = pd.read_csv(io.StringIO(temp), sep=";", encoding = "ISO-8859-1", decimal= ',')
    print (df)
          A      B
    0  Emma -20.50
    1  Filo -15.75
    2  Theo  17.23
    
    print (df.dtypes)
    A     object
    B    float64
    dtype: object
    

    编辑:

    我认为问题可能是一些小数是. 和一些,,然后使用converters

    import pandas as pd
    import io
    
    temp=u"""A;B
    0;Emma;-20,50
    1;Filo;-15.75
    2;Theo;17,23"""
    
    
    def converter(x):
        return float(x.replace(',','.'))
    
    #define each column
    converters={'B': converter}
    
    #after testing replace io.StringIO(temp) to filename
    df = pd.read_csv(io.StringIO(temp), 
                     sep=";", 
                     encoding = "ISO-8859-1", 
                     converters=converters)
    print (df)
    
    0  Emma -20.50
    1  Filo -15.75
    2  Theo  17.23
    
    print (df.dtypes)
    A     object
    B    float64
    dtype: object
    

    【讨论】:

    • 感谢您的快速回答,但对我来说仍然无法正常工作。我觉得这很奇怪。
    • 不,这不是问题。所有小数实际上都是','。但是有一些 0 值(所以没有小数)和一些 NaN。
    • 如果数据不保密,是否可以分享 csv - 通过 Dropbox、ggogle 文档...?
    • 抱歉,无法分享。
    • 确实在 csv 中有一些 '.' (如格式 1.230,45)但它们位于其他列中。难道他们仍然阻止将剩余的行转换为浮点数?
    猜你喜欢
    • 2021-11-18
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2023-03-18
    • 2015-06-11
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多