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



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

以下是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

感谢您的帮助

FX-

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

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

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

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

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

最新更新