【问题标题】:Why is NaN considered as a float?为什么 NaN 被视为浮点数?
【发布时间】:2018-07-11 13:19:30
【问题描述】:

pandas 中,当我们尝试将包含NaN 值的系列转换为具有如下所示sn-p 的整数时

df.A = df.A.apply(int),经常看到报错信息

ValueError: cannot convert float NaN to integer

我了解NaN 值无法转换为整数。但我很好奇在这种情况下抛出的ValueError。它说 float NaN 不能转换为整数。

NaN 值被视为浮点对象有什么具体原因吗?还是显示的错误消息有问题?

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

简短的回答是IEEE 754NaN 指定为float 值。

至于如何将pd.Series 转换为特定的数字数据类型,我更喜欢在可能的情况下使用pd.to_numeric。下面的例子说明了原因。

import pandas as pd
import numpy as np

s = pd.Series([1, 2.5, 3, 4, 5.5])        # s.dtype = float64
s = s.astype(float)                       # s.dtype = float64
s = pd.to_numeric(s, downcast='float')    # s.dtype = float32

t = pd.Series([1, np.nan, 3, 4, 5])       # s.dtype = float64
t = t.astype(int)                         # ValueError
t = pd.to_numeric(t, downcast='integer')  # s.dtype = float64

u = pd.Series([1, 2, 3, 4, 5, 6])         # s.dtype = int64
u = u.astype(int)                         # s.dtype = int32
u = pd.to_numeric(u, downcast='integer')  # s.dtype = int8

【讨论】:

  • 我不熟悉to_numeric,很好。
【解决方案2】:

值得思考说任何数字“是”float 意味着什么。在 CPython 中,float 类型是使用 C 中的 double 实现的,这意味着它们使用 IEEE 754 双精度。

在该标准中,有特定的位序列对应于可以在系统中表示的每个浮点数(请注意,并非所有可能的上下限之间的数字都可以表示)。

此外,还有一些特殊的位序列与“常规”数字不对应,因此无法转换为整数。

  • 两个无穷大:+∞ 和 -∞。
  • 两种NaN:一种是安静的NaNqNaN)和一种信号NaNsNaN)。

要使用此类值构建float,您可以使用以下调用:

nan = float('nan')
inf = float('inf')

在将这些值传递给int 构造函数时,您会看到同样的错误:

>>> int(nan)
ValueError: cannot convert float NaN to integer

>>> int(inf)
OverflowError: cannot convert float infinity to integer

【讨论】:

    猜你喜欢
    • 2012-03-17
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2012-03-09
    • 2018-09-29
    • 1970-01-01
    • 2020-11-11
    相关资源
    最近更新 更多