【问题标题】:Using astype in Pandas does not give the expected result在 Pandas 中使用 astype 不会产生预期的结果
【发布时间】:2020-07-22 09:12:46
【问题描述】:

我正在尝试在 Pandas 数据框中将浮点数转换为 int。我通常使用.astype('int64'),但在这种情况下,它不起作用。 这是我正在使用的代码:

import pandas as pd
d = {'test': [1]}
df = pd.DataFrame(columns= ['test'], data =d)

df['test'] = 60590820065001969.0
df['test'].astype('int64')

这是我得到的结果:

0    60590820065001968
Name: test, dtype: int64

请注意这些数字有何不同(浮点数以 69 结尾,整数版本以 68 结尾)。

如果我尝试一个较小的数字,通过删除前 2 位数字,那么它可以正常工作:

df['test'] = 590820065001969.0
df['test'].astype('int64')

给我:

0    590820065001969
Name: test, dtype: int64

这让我觉得它可能与数字大小有关,但我不确定它是什么。任何人都可以在这里发现问题吗? 顺便说一句,我使用的是 Python 3。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    60590820065001969.0 太大,python 无法以浮点格式精确表示。因此,python 会选择它能够正确表示的最接近的值。

    使用decimal

    In [16]: import decimal
    
    In [17]: a = decimal.Decimal("60590820065001969.0")
    
    In [18]: int(a)
    Out[18]: 60590820065001969
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 2017-05-03
      相关资源
      最近更新 更多