为了检查值是否为NaNisnull()或notnull()可以使用函数。
In [1]: import numpy as np In [2]: import pandas as pd In [3]: ser = pd.Series([1, 2, np.nan, 4]) In [4]: pd.isnull(ser) Out[4]: 0 False 1 False 2 True 3 False dtype: bool
请注意,np.nan == np.nan返回False,因此应避免与np.nan进行比较:
In [5]: ser == np.nan Out[5]: 0 False 1 False 2 False 3 False dtype: bool
这两个函数也被定义为Series和DataFrames上的方法。
In [6]: ser.isnull() Out[6]: 0 False 1 False 2 True 3 False dtype: bool
在DataFrames上测试:
In [7]: df = pd.DataFrame({'A': [1, np.nan, 3], 'B': [np.nan, 5, 6]})
In [8]: print(df)
Out[8]:
A B
0 1.0 NaN
1 NaN 5.0
2 3.0 6.0
In [9]: df.isnull() # If the value is NaN, returns True.
Out[9]:
A B
0 False True
1 True False
2 False False
In [10]: df.notnull() # Opposite of .isnull(). If the value is not NaN, returns True.
Out[10]:
A B
0 True False
1 False True
2 True True