How can I check for NaN values?

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

    How to remove NaN (float) item(s) from a list of mixed data types

    If you have mixed types in an iterable, here is a solution that does not use 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]

    Short-circuit evaluation means that isnan will not be called on values that are not of type 'float', as False and (…) quickly evaluates to False without having to evaluate the right-hand side.

提交回复
热议问题