【问题标题】:Is it possible to set a number to NaN or infinity?是否可以将数字设置为 NaN 或无穷大?
【发布时间】:2011-07-23 06:20:07
【问题描述】:

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

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

【问题讨论】:

  • stackoverflow.com/questions/944700 告诉您如何检查 NaN。对于 Inf 和 -Inf,您可以使用 == 进行测试,但由于 IEEE754 对 NaN 的规则,这对 NaN 不起作用。

标签: python numeric nan infinite


【解决方案1】:

或者你可以计算它们

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

【讨论】:

    【解决方案2】:

    是否可以将数字设置为 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")float("InFiNiTy")
    • cmathnumpy 常量返回纯 Python float 对象。
    • numpy.NINF 实际上是我所知道的唯一一个不需要- 的常量。
    • 可以使用complexcmath 创建复杂的NaN 和Infinity:

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

    再说几句:

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

      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.arraynumpy.array)中,那么数组的类型必须floatcomplex,否则它会尝试将其向下转换为数组类型!

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

    【讨论】:

    • 注意:math.isnan 不适用于复数。请改用math.isnan(x.real) or math.isnan(x.imag)
    【解决方案3】:

    使用 Python 2.4 时,试试

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

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 在 python >= 2.6 上,你可以使用math.isnan()math.isinf()
      • numpy 如果你想要的只是NaNinf,那是相当重要的导入
      • 如果您只需要NaNInf,则可以使用from numpy import nan, inf,自提出此问题以来就已存在。
      【解决方案5】:

      使用float()从字符串转换:

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

      【讨论】:

      • 这将教会我在第二遍阅读问题之前不要插话!对不起!就是说,这样说也没什么坏处,因为它很容易掉入陷阱,NaN!= NaN
      • 另请注意:>>> float('Inf')-float('Inf') ===> nan
      • 注:float('Inf')*0float('Inf')/float('Inf') ==> 南。还有float('Inf')*-1 ==> -inf
      猜你喜欢
      • 2012-07-10
      • 2021-07-02
      • 2016-10-16
      • 2018-10-13
      • 2014-02-14
      • 2021-02-10
      • 2019-10-11
      相关资源
      最近更新 更多