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


202

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

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


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

我认为最可靠的方法是使用,isinf和isnan提供的适当功能numpy。请参阅下面的答案。
— Olivier Verdier

Answers:


271

使用float()以下内容从字符串进行转换:

>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False

1
那将教我在第二次阅读问题之前不要胡扯!!抱歉! 话虽如此,所以说同样的话不会有任何伤害,因为这是一个容易陷入的陷阱,NaN!= NaN
— David Heffernan

2
还要注意:>>> float('Inf')-float('Inf')===> nan
— ntg 2014年

76

是的,您可以使用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

21
在python> = 2.6上,您可以仅使用math.isnan()andmath.isinf()
— Agos,

8
numpy如果您想要的是NaN或者inf
— -cz

1
如果您所需要的只是NaN或Inf,那么from numpy import nan, inf自提出这个问题以来一直存在。
— andrewgu '19

37

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

是的,实际上有几种方法。一些工作没有任何导入,而另一些工作则需要import,但是对于此答案,我将概述中的库限制为standard-library和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")或float("InFiNiTy")。
  • 的 cmath和numpy常量返回普通的Python float对象。
  • 的 numpy.NINF其实是我知道的,不需要的唯一不变的-。
  • 可以使用complex和创建复杂的NaN和Infinitycmath:

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

再说几句话:

  • 的 cmath和numpy功能也工作了复杂的对象,他们会检查是否真实或虚部是NAN或无穷。
  • 该numpy功能也适用于numpy数组以及可以转换为一个数组的所有内容(例如列表,元组等)。
  • 还有一些函数可以在NumPy:numpy.isposinf和中显式检查正负无穷大numpy.isneginf。
  • 熊猫提供了两个附加功能来检查NaN:pandas.isna和pandas.isnull(但不仅是NaN,它还与None和相匹配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.array或numpy.array)中,则数组的类型必须为float或,complex因为否则它将尝试将其向下转换为数组的类型!

>>> 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

1
注意: math.isnan不适用于复数。使用math.isnan(x.real) or math.isnan(x.imag)代替。
— 乔纳森·H

2

使用Python 2.4时,请尝试

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.