float(nan')表示nan(不是数字)。但我该如何检查呢?


当前回答

这里有三种方法可以测试变量是否为“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

其他回答

事实上我刚碰到这个,但对我来说,它是在检查nan、-inf或inf

if float('-inf') < float(num) < float('inf'):

这对于数字是正确的,对于nan和inf都是错误的,对于字符串或其他类型(这可能是一件好事)会引发异常。此外,这不需要导入任何库,如math或numpy(numpy非常大,它的大小是任何编译应用程序的两倍)。

当python<2.6时

def isNaN(x):
    return str(float(x)).lower() == 'nan'

这适用于Solaris 5.9机箱上的python 2.5.1和Ubuntu 10上的python 2.6.5

numpy.isnan(数字)告诉你它是不是NaN。

使用math.isnan:

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True

用于浮球类型

>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False