在Python中可以将数组的元素设置为NaN吗?
另外,是否可以将变量设置为+/-∞?如果是,有没有函数来检查一个数字是不是无穷大?
在Python中可以将数组的元素设置为NaN吗?
另外,是否可以将变量设置为+/-∞?如果是,有没有函数来检查一个数字是不是无穷大?
当前回答
使用float()从字符串转换:
>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
其他回答
是否可以将一个数字设置为NaN或无穷大?
是的,事实上有几种方法。一些库不需要任何导入,而另一些则需要导入,但是对于这个答案,我将在概述中限制标准库和NumPy(它不是标准库,而是一个非常常见的第三方库)。
下表总结了如何创建一个非数字或正或负无穷大浮点数:
╒══════════╤══════════════╤════════════════════╤════════════════════╕
│ 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 │
╘══════════╧══════════════╧════════════════════╧════════════════════╛
对表格的一些备注:
The float constructor is actually case-insensitive, so you can also use float("NaN") or float("InFiNiTy"). The cmath and numpy constants return plain Python float objects. The numpy.NINF is actually the only constant I know of that doesn't require the -. It is possible to create complex NaN and Infinity with complex and 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 │ ╘══════════╧════════════════╧═════════════════╧═════════════════════╧══════════════════════╛ The options with ¹ return a plain float, not a complex.
有没有函数可以检查一个数字是不是无穷大?
是的,有-事实上有几个NaN, Infinity,以及NaN和Inf的函数。然而,这些预定义的函数不是内置的,它们总是需要导入:
╒══════════╤═════════════╤════════════════╤════════════════════╕
│ 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 │
╘══════════╧═════════════╧════════════════╧════════════════════╛
再说几句:
The cmath and numpy functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity. The numpy functions also work for numpy arrays and everything that can be converted to one (like lists, tuple, etc.) There are also functions that explicitly check for positive and negative infinity in NumPy: numpy.isposinf and numpy.isneginf. Pandas offers two additional functions to check for NaN: pandas.isna and pandas.isnull (but not only NaN, it matches also None and NaT) Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here): 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或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
当使用Python 2.4时,请尝试
inf = float("9e999")
nan = inf - inf
当我将simplejson移植到运行Python 2.4, float(“9e999”)的嵌入式设备时,我面临着这个问题。不要使用inf = 9e999,你需要从字符串转换它。 -inf得到-∞。
是的,您可以使用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
使用float()从字符串转换:
>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
或者你可以计算它们
Python 3.9 on Windows 10
>>> import sys
>>> Inf = sys.float_info.max * 10
>>> Inf
inf
>>> NaN = Inf - Inf
>>> NaN
nan