使用pandas读取一个数据表,怎么判断表中的某一个数据data的值是否为nan呢?
import pandas as pd
mydf=pd.read_csv('mydata.csv')
print(mydf)
print('\n=================================')
mydf.iloc[1,2]=pd.np.nan
mydf.iloc[2,1]=pd.np.nan
print(mydf)
print('\n=================================')
print(mydf.iloc[2,1])
print(pd.np.nan)
print(mydf.iloc[2, 1] is pd.np.nan)#错误
print(mydf.iloc[2, 1] == pd.np.nan)#错误
print(pd.isnull(mydf.iloc[2, 1]))#正确,判断某个数据是否是NaN
print(mydf.iloc[:,2].isnull())#正确,判断series里的值是否为NaN
print('\n=================================')
print(mydf.iloc[2, 2])
print(mydf.iloc[2, 2] is pd.np.nan)
print(mydf.iloc[2, 2] == pd.np.nan)
print(pd.isnull(mydf.iloc[2, 2]))#正确,判断某个数据是否是NaN
output:
user_id order_id product_name
0 1 2001 snacks
1 2 2002 apple
2 3 2003 noodle
3 4 2004 mutton
4 5 2006 bread
=================================
user_id order_id product_name
0 1 2001.0 snacks
1 2 2002.0 NaN
2 3 NaN noodle
3 4 2004.0 mutton
4 5 2006.0 bread
=================================
nan
nan
False
False
True
0 False
1 True
2 False
3 False
4 False
Name: product_name, dtype: bool
=================================
noodle
False
False
False
从上面的code snippet以及output可以看出,数据表‘mydata.csv’中第2行第1列 mydf.iloc[2, 1] 的值是NaN
但是使用 is 和 == 来判断这个数据是否为NaN时,都无法得到正确的判断结果
正确的方法是使用 pandas.isnull()这个接口来判断
pd.isnull(mydf.iloc[2, 1])