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


当前回答

比较pd.isna、math.isnan和np.isnan及其处理不同类型对象的灵活性。

下表显示了是否可以使用给定方法检查对象类型:


+------------+-----+---------+------+--------+------+
|   Method   | NaN | numeric | None | string | list |
+------------+-----+---------+------+--------+------+
| pd.isna    | yes | yes     | yes  | yes    | yes  |
| math.isnan | yes | yes     | no   | no     | no   |
| np.isnan   | yes | yes     | no   | no     | yes  | <-- # will error on mixed type list
+------------+-----+---------+------+--------+------+

pd.isna文件

检查不同类型缺失值的最灵活方法。


所有答案都没有涵盖pd.isna的灵活性。虽然math.isnan和np.isnan将为NaN值返回True,但您无法检查None或字符串等不同类型的对象。这两个方法都会返回错误,因此检查混合类型的列表会很麻烦。而pd.isna是灵活的,它将为不同类型返回正确的布尔值:

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: missing_values = [3, None, np.NaN, pd.NA, pd.NaT, '10']

In [4]: pd.isna(missing_values)
Out[4]: array([False,  True,  True,  True,  True, False])

其他回答

另一种方法是,如果你坚持低于2.6,你没有numpy,也没有IEEE 754支持:

def isNaN(x):
    return str(x) == str(1e400*0)

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

似乎检查它是否等于自身(x!=x)是最快的。

import pandas as pd 
import numpy as np 
import math 

x = float('nan')

%timeit x != x
44.8 ns ± 0.152 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit math.isnan(x)
94.2 ns ± 0.955 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit pd.isna(x)
281 ns ± 5.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.isnan(x)
1.38 µs ± 15.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

math.isnan()

或将数字与自身进行比较。NaN总是!=NaN,否则(例如,如果是数字),比较应成功。

在Python 3.6中,检查字符串值x math.isnan(x)和np.issan(x)会引发错误。所以我无法检查给定值是否为NaN,如果我事先不知道它是一个数字。以下内容似乎解决了这个问题

if str(x)=='nan' and type(x)!='str':
    print ('NaN')
else:
    print ('non NaN')