How can I check for NaN values?

后端 未结 17 2174
盖世英雄少女心
盖世英雄少女心 2020-11-22 05:02

float(\'nan\') results in Nan (not a number). But how do I check for it? Should be very easy, but I cannot find it.

17条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:49

    All the methods to tell if the variable is NaN or None:

    None type

    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 "", line 1, in 
        math.isnan(a)
    TypeError: a float is required
    
    In [10]: len(a) == 0
    Traceback (most recent call last):
      File "", line 1, in 
        len(a) == 0
    TypeError: object of type 'NoneType' has no len()
    

    NaN type

    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
    

提交回复
热议问题