float(nan')表示nan(不是数字)。但我该如何检查呢?


当前回答

使用math.isnan:

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True

其他回答

math.isnan()

或将数字与自身进行比较。NaN总是!=NaN,否则(例如,如果是数字),比较应成功。

numpy.isnan(数字)告诉你它是不是NaN。

判断变量是NaN还是None的所有方法:

无类型

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN类型

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

我进入这篇文章,因为我在功能方面遇到了一些问题:

math.isnan()

运行此代码时出现问题:

a = "hello"
math.isnan(a)

它引发了异常。我的解决方案是再做一次检查:

def is_nan(x):
    return isinstance(x, float) and math.isnan(x)

我正在从一个web服务接收数据,该服务将NaN作为字符串“NaN”发送。但我的数据中也可能有其他类型的字符串,所以简单的float(value)可能会引发异常。我使用了接受答案的以下变体:

def isnan(value):
  try:
      import math
      return math.isnan(float(value))
  except:
      return False

要求:

isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True