是否可以将数字设置为 NaN 或无穷大?

Is it possible to set a number to NaN or infinity?

提问人:zzzbbx 提问时间:3/26/2011 最后编辑:nbrozzzbbx 更新时间:2/4/2023 访问量:378331

问:

是否可以在 Python 中将数组的元素设置为?NaN

此外,是否可以将变量设置为 +/- 无穷大?如果是这样,是否有任何函数可以检查一个数字是否是无穷大?

数值的 无限

评论

4赞 David Heffernan 3/26/2011
stackoverflow.com/questions/944700 告诉您如何检查 NaN。对于 Inf 和 -Inf,您可以使用 == 进行测试,但由于 NaN 的IEEE754规则,这不适用于 NaN。

答:

307赞 moinudin 3/26/2011 #1

使用以下方法从字符串强制转换:float()

>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
83赞 Olivier Verdier 3/26/2011 #2

是的,您可以使用 numpy

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True
2赞 user6458202 2/1/2017 #3

使用 Python 2.4 时,请尝试

inf = float("9e999")
nan = inf - inf

当我将 simplejson 移植到运行 Python 2.4 的嵌入式设备时,我遇到了这个问题,修复了它。不要使用 ,您需要从字符串转换它。 给出 .float("9e999")inf = 9e999-inf-Infinity

55赞 MSeifert 2/1/2017 #4

是否可以将数字设置为 NaN 或无穷大?

是的,实际上有几种方法。一些工作没有任何导入,而另一些则需要 ,但是对于这个答案,我将概述中的库限制为标准库和 NumPy(这不是标准库,而是一个非常常见的第三方库)。import

下表总结了如何创建非数字或正无穷大或负无穷大的方法:float

╒══════════╤══════════════╤════════════════════╤════════════════════╕
│   result │ NaN          │ Infinity           │ -Infinity          │
│ module   │              │                    │                    │
╞══════════╪══════════════╪════════════════════╪════════════════════╡
│ built-in │ float("nan") │ float("inf")       │ -float("inf")      │
│          │              │ float("infinity")  │ -float("infinity") │
│          │              │ float("+inf")      │ float("-inf")      │
│          │              │ float("+infinity") │ float("-infinity") │
├──────────┼──────────────┼────────────────────┼────────────────────┤
│ math     │ math.nan     │ math.inf           │ -math.inf          │
├──────────┼──────────────┼────────────────────┼────────────────────┤
│ cmath    │ cmath.nan    │ cmath.inf          │ -cmath.inf         │
├──────────┼──────────────┼────────────────────┼────────────────────┤
│ numpy    │ numpy.nan    │ numpy.PINF         │ numpy.NINF         │
│          │ numpy.NaN    │ numpy.inf          │ -numpy.inf         │
│          │ numpy.NAN    │ numpy.infty        │ -numpy.infty       │
│          │              │ numpy.Inf          │ -numpy.Inf         │
│          │              │ numpy.Infinity     │ -numpy.Infinity    │
╘══════════╧══════════════╧════════════════════╧════════════════════╛

有几点意见:

  • 构造函数实际上不区分大小写,因此也可以使用 或 .floatfloat("NaN")float("InFiNiTy")
  • and 常量返回纯 Python 对象。cmathnumpyfloat
  • 这实际上是我所知道的唯一不需要 .numpy.NINF-
  • 可以使用 和 创建复杂的 NaN 和 Infinity:complexcmath

    ╒══════════╤════════════════╤═════════════════╤═════════════════════╤══════════════════════╕
    │   result │ NaN+0j         │ 0+NaNj          │ Inf+0j              │ 0+Infj               │
    │ module   │                │                 │                     │                      │
    ╞══════════╪════════════════╪═════════════════╪═════════════════════╪══════════════════════╡
    │ built-in │ complex("nan") │ complex("nanj") │ complex("inf")      │ complex("infj")      │
    │          │                │                 │ complex("infinity") │ complex("infinityj") │
    ├──────────┼────────────────┼─────────────────┼─────────────────────┼──────────────────────┤
    │ cmath    │ cmath.nan ¹    │ cmath.nanj      │ cmath.inf ¹         │ cmath.infj           │
    ╘══════════╧════════════════╧═════════════════╧═════════════════════╧══════════════════════╛
    

    带有 ¹ 的选项返回普通 ,而不是 。floatcomplex

有什么函数可以检查一个数字是否是无穷大的吗?

是的,有 - 实际上 NaN、Infinity 有几个函数,而 Nan 和 Inf 都没有。但是,这些预定义函数不是内置的,它们始终需要:import

╒══════════╤═════════════╤════════════════╤════════════════════╕
│      for │ NaN         │ Infinity or    │ not NaN and        │
│          │             │ -Infinity      │ not Infinity and   │
│ module   │             │                │ not -Infinity      │
╞══════════╪═════════════╪════════════════╪════════════════════╡
│ math     │ math.isnan  │ math.isinf     │ math.isfinite      │
├──────────┼─────────────┼────────────────┼────────────────────┤
│ cmath    │ cmath.isnan │ cmath.isinf    │ cmath.isfinite     │
├──────────┼─────────────┼────────────────┼────────────────────┤
│ numpy    │ numpy.isnan │ numpy.isinf    │ numpy.isfinite     │
╘══════════╧═════════════╧════════════════╧════════════════════╛

再说几句:

  • 和函数也适用于复杂对象,它们将检查实部或虚部是 NaN 还是 Infinity。cmathnumpy
  • 这些函数也适用于数组和可以转换为数组的所有内容(如列表、元组等)numpynumpy
  • 还有一些函数可以显式检查 NumPy 中的正无穷大和负无穷大: 和 .numpy.isposinfnumpy.isneginf
  • Pandas 提供了两个额外的函数来检查:pandas.isnapandas.isnull(但不仅是 NaN,它还匹配和NaNNoneNaT)
  • 即使没有内置函数,自己创建它们也很容易(我在这里忽略了类型检查和文档):

    def isnan(value):
        return value != value  # NaN is not equal to anything, not even itself
    
    infinity = float("infinity")
    
    def isinf(value):
        return abs(value) == infinity 
    
    def isfinite(value):
        return not (isnan(value) or isinf(value))
    

总结这些函数的预期结果(假设输入是浮点数):

╒════════════════╤═══════╤════════════╤═════════════╤══════════════════╕
│          input │ NaN   │ Infinity   │ -Infinity   │ something else   │
│ function       │       │            │             │                  │
╞════════════════╪═══════╪════════════╪═════════════╪══════════════════╡
│ isnan          │ True  │ False      │ False       │ False            │
├────────────────┼───────┼────────────┼─────────────┼──────────────────┤
│ isinf          │ False │ True       │ True        │ False            │
├────────────────┼───────┼────────────┼─────────────┼──────────────────┤
│ isfinite       │ False │ False      │ False       │ True             │
╘════════════════╧═══════╧════════════╧═════════════╧══════════════════╛

是否可以在 Python 中将数组的元素设置为 NaN?

在列表中没问题,您始终可以在此处包含 NaN(或 Infinity):

>>> [math.nan, math.inf, -math.inf, 1]  # python list
[nan, inf, -inf, 1]

但是,如果要将其包含在(例如 或 )中,则数组的类型必须为 or,否则它将尝试将其转换为数组类型!arrayarray.arraynumpy.arrayfloatcomplex

>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan,  0.,  0.])

>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])

>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer
0赞 Coder436 4/23/2021 #5

或者你可以计算它们

Python 3.9 on Windows 10
>>> import sys
>>> Inf = sys.float_info.max * 10
>>> Inf
inf
>>> NaN = Inf - Inf
>>> NaN
nan