import numpy as np
def check_nan(x):
if isinstance(x, (int, float, np.number)) and np.isnan(x):
print(f'{x} is np.nan')
else:
print(f'{x} is not np.nan')
check_nan(1)
check_nan(np.nan)
check_nan(None)
check_nan('abc')
输出为
1 is not np.nan
nan is np.nan
None is not np.nan
abc is not np.nan
之所以这样写,是因为None和字符串等传入nan会报错,需要try+except捕捉。