Pandas : 将字符串转换为浮点数时出现精度错误

Pandas : Precision error when converting string to float

使用 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

感谢您的帮助

外汇

浮点数在计算机硬件中表示为基数为 2(二进制)的分数。大多数小数不能精确地表示为二进制小数。

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

您实际上可以通过以下运行看到这对应于哪个十进制数:

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

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