【问题标题】:When reading CSV with `pd.read_csv`, the decimal places change (Pandas) [duplicate]使用`pd.read_csv`读取CSV时,小数位会发生变化(熊猫)[重复]
【发布时间】:2018-01-10 09:36:59
【问题描述】:
excel = pd.read_csv("EH_damages.csv")

你好! 我使用上面的代码将 csv 文件读入 python。但是,原始 excel 中的 0.289798953 更改为 0.289799。即使我在 excel 中将数字保存为文本模式,python 仍然将其读取为浮点数,并且数字的位数更少,例如 0.289799

我的代码有什么问题?谢谢!!

【问题讨论】:

    标签: python excel pandas csv dataframe


    【解决方案1】:

    并非所有小数都可以用浮点数精确表示,但这似乎不是 成为这里的主要问题。您所看到的只是 Pandas 格式化的方式 打印时默认为 DataFrames。存储在 DataFrame 中的实际浮点数 可能有更多的数字。

    例如,使用这个 DataFrame:

    import pandas as pd
    df = pd.DataFrame({'foo':[0.289798953]})
    

    你看到了:

    print(df)
    #         foo
    # 0  0.289799
    

    但实际浮点值还是0.289798953

    print(df.ix[0, 'foo'])
    # 0.289798953
    

    您可以通过设置告诉 Pandas 显示小数点后 9 位:

    pd.options.display.float_format = '{:.9f}'.format
    

    或者,如cᴏʟᴅsᴘᴇᴇᴅ suggestspd.set_option('precision', 9)。 然后打印DataFrame显示:

    print(df)
    #           foo
    # 0 0.289798953
    

    您可以阅读更多关于可用的options here

    【讨论】:

    • 可能更简单:pd.set_option('precision', 9)(或任何其他号码)
    • @cᴏʟᴅsᴘᴇᴇᴅ:感谢改进;我不知道。
    • 是的。在寻找这个问题的答案时,遇到了链接到docs 的骗子。
    猜你喜欢
    • 2018-10-17
    • 2021-04-25
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多