如何检查 NaN 值?

float('nan')结果为 Nan(不是数字)。但是,如何检查呢?应该很容易,但是我找不到。

答案

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
def isNaN(num):
    return num != num

numpy.isnan(number)告诉您是否为NaN

import pandas as pd
import numpy as np
import math

#For single variable all three libraries return single boolean
x1 = float("nan")

print(f"It's pd.isna  : {pd.isna(x1)}")
print(f"It's np.isnan  : {np.isnan(x1)}")
print(f"It's math.isnan : {math.isnan(x1)}")
It's pd.isna  : True
It's np.isnan  : True
It's math.isnan  : True
import numpy as np

def is_nan(x):
    return (x is np.nan or x != x)
values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
    print "{:<8} : {}".format(repr(value), is_nan(value))
nan      : True
nan      : True
55       : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False
if float('-inf') < float(num) < float('inf'):

math.isnan()

或将数字与其本身进行比较。 NaN 始终为!= NaN,否则(例如,如果数字)比较将成功。

def isNaN(x):
    return str(x) == str(1e400*0)
math.isnan()
a = "hello"
math.isnan(a)
def is_nan(x):
    return isinstance(x, float) and math.isnan(x)
def isNaN(x):
    return str(float(x)).lower() == 'nan'