首页 > 解决方案 > Pandas:将字符串转换为浮点数时出现精度错误

问题描述

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

谢谢你的帮助

外汇

标签: stringpandasprecisionfloating-accuracy

解决方案


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

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

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

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

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


推荐阅读