【问题标题】:Pandas : Precision error when converting string to floatPandas:将字符串转换为浮点数时出现精度错误
【发布时间】:2019-04-15 21:18:44
【问题描述】:

使用 pandas 处理时间戳,我将两列连接起来,然后将结果转换为浮点数。看来,当我显示两列时,我观察到两个不同的结果。从字符串到浮点数的转换如何影响值?感谢您的帮助。

这是data.csv文件的内容

epoch_day,epoch_ns
1533081601,224423000

这是我的测试程序:

import pandas as pd
pd.options.display.float_format = '{:.10f}'.format
df_mid = pd.read_csv("data.csv")

df_mid['result_1']=df_mid['epoch_day'].astype(str).str.cat(df_mid['epoch_ns'].astype(str), sep =".")
df_mid['result_2'] = df_mid['epoch_day'].astype(str).str.cat(df_mid['epoch_ns'].astype(str), sep =".").astype(float)
print(df_mid)

结果是:

   epoch_day   epoch_ns              result_1              result_2
0  1533081601  224423000  1533081601.224423000 1533081601.2244229317

感谢您的帮助

外汇

【问题讨论】:

    标签: string pandas precision floating-accuracy


    【解决方案1】:

    浮点数在计算机硬件中表示为以 2 为底的(二进制)分数。大多数十进制分数不能完全表示为二进制分数。

    当你转换你的字符串时,python 会创建一个浮点数,它是你输入的最接近的二进制分数。

    您实际上可以通过运行以下命令来查看它对应于哪个十进制数:

    from decimal import Decimal
    Decimal(1533081601.224423000)
    OUTPUT: Decimal('1533081601.224422931671142578125')
    

    您可以查看 Python 文档以获取更多信息 https://docs.python.org/2/tutorial/floatingpoint.html

    【讨论】:

    • 非常感谢@guilherm-costa 的解释。
    • 感谢您的反馈。你能接受答案吗?
    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 2020-08-06
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多