How can I check for NaN values?

后端 未结 17 2168
盖世英雄少女心
盖世英雄少女心 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:47

    here is an answer working with:

    • NaN implementations respecting IEEE 754 standard
      • ie: python's NaN: float('nan'), numpy.nan...
    • any other objects: string or whatever (does not raise exceptions if encountered)

    A NaN implemented following the standard, is the only value for which the inequality comparison with itself should return True:

    def is_nan(x):
        return (x != x)
    

    And some examples:

    import numpy as np
    values = [float('nan'), np.nan, 55, "string", lambda x : x]
    for value in values:
        print(f"{repr(value):<8} : {is_nan(value)}")
    

    Output:

    nan      : True
    nan      : True
    55       : False
    'string' : False
     at 0x000000000927BF28> : False
    

提交回复
热议问题