233

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

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

4

5 回答 5

297

使用以下字符串转换float()

>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
于 2011-03-25T22:25:46.467 回答
80

是的,您可以使用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
于 2011-03-26T00:19:43.537 回答
48

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

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

下表总结了如何创建非数字或正或负无穷大的方法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    │
╘══════════╧══════════════╧════════════════════╧════════════════════╛

对表的几点说明:

  • 构造float函数实际上是不区分大小写的,所以你也可以使用float("NaN")or float("InFiNiTy")
  • cmath和常量返回普通的numpyPythonfloat对象。
  • 实际上是我所知道的numpy.NINF唯一一个不需要-.
  • 可以使用 和 创建复杂的 NaN 和complexInfinity cmath

    ╒══════════╤════════════════╤═════════════════╤═════════════════════╤══════════════════════╕
    │   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           │
    ╘══════════╧════════════════╧═════════════════╧═════════════════════╧══════════════════════╛
    

    带有 ¹ 的选项返回一个普通的float,而不是一个complex.

是否有任何功能可以检查数字是否为无穷大?

是的——事实上,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     │
╘══════════╧═════════════╧════════════════╧════════════════════╛

再说几句:

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

    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]

但是,如果您想将它包含在array(例如array.arrayor numpy.array)中,那么数组的类型必须floatorcomplex因为否则它将尝试将其向下转换为数组类型!

>>> 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
于 2017-02-01T01:16:09.080 回答
2

使用 Python 2.4 时,请尝试

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

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

于 2017-02-01T00:54:26.700 回答
0

或者你可以计算它们

Python 3.9 on Windows 10
>>> import sys
>>> Inf = sys.float_info.max * 10
>>> Inf
inf
>>> NaN = Inf - Inf
>>> NaN
nan
于 2021-04-22T16:05:27.793 回答