string - 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
谢谢你的帮助
外汇
解决方案
浮点数在计算机硬件中表示为以 2 为底的(二进制)分数。大多数十进制分数不能完全表示为二进制分数。
当您转换字符串时,python 会创建一个浮点数,它是您输入的最接近的二进制分数。
您实际上可以通过运行以下命令来查看它对应于哪个十进制数:
from decimal import Decimal
Decimal(1533081601.224423000)
OUTPUT: Decimal('1533081601.224422931671142578125')
您可以查看 Python 文档以获取更多信息https://docs.python.org/2/tutorial/floatingpoint.html
推荐阅读
- openlayers-5 - Openlayers 5 - 动态变化的交互
- java - 超类/子类继承范围验证
- xamarin.forms - 无法解析函数
与“全部链接” - r - 将 cumsum 重置为变量中的值
- java - 如何在 Spring Boot 中使用 ORDER BY?
- c# - 将datagridview的阿拉伯语数据保存在数据库中
- css - 为什么在 CSS 网格中使用 fr 单位会导致 chrome 出现这种行为?
- java - 通过 Jackson 序列化 java.sql.Date,同时考虑夏令时
- python - 将函数嵌套到函数中
- mongodb - Mongoose 是否有办法在一个查询中查询文档并在不存在时创建新文档?