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


当前回答

测试NaN的通常方法是查看它是否等于自身:

def isNaN(num):
    return num != num

其他回答

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

测试NaN的通常方法是查看它是否等于自身:

def isNaN(num):
    return num != num

另一种方法是,如果你坚持低于2.6,你没有numpy,也没有IEEE 754支持:

def isNaN(x):
    return str(x) == str(1e400*0)

我正在从一个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

如何从混合数据类型列表中删除NaN(float)项

如果在可迭代的中有混合类型,这里有一个不使用numpy的解决方案:

from math import isnan

Z = ['a','b', float('NaN'), 'd', float('1.1024')]

[x for x in Z if not (
                      type(x) == float # let's drop all float values…
                      and isnan(x) # … but only if they are nan
                      )]
['a', 'b', 'd', 1.1024]

短路求值意味着不会对非“float”类型的值调用isnan,因为False和(…)很快求值为False,而无需对右侧求值。