np.nan, np.isnan, None, pd.isnull, pd.isna 整理与小结
np.nan
np.nan not a member nan的含义是“not a number“,它是对array中缺失的数值 的占位符 type 为 float 因为代表缺失的数值,np.nan的type是float 可参与计算 np.nan的type是float,所以np.nan可参与计算,且占主导地位,也就是算出的值都为np.nan 不等于自身 如果用np.nan==np.nan,会发现返回的结果为False,如果用np.nan in array,也不能发现array中是否包含np.nan np.isnan判断是否存在np.nan np.nan因为没有等于的概念,所以要判断是否存在np.nan,只可以用np.isnan来判断 np.isnan只可以判断数值型 如果用np.isnan对其余type的array判断,会报错,np.isnan只可以判断数字型array
忽略np.nan的numpy计算 nansum() nanmax() nanmin() nanargmax() nanargmin()
None
None NoneType None的type为NoneType,是python内置的 不可参与计算 None不可参与计算,否则报错 None is None 或者 None==None 这两种方式返回值都是True
pd.isnull 和 pd.isna
pd.isnull pd.isna pd.isnull 和 pd.isna是同一个东西 用命令pd.isnull==pd.isna,会发现返回值为True None和np.nan在pandas中都是缺省值 None和np.nan都会被pd.isnull或者pd.isna判断为True 可以判断List或者单独一个值 pd.isnull和pd.isna的判断对象可以为一个值或者一个list pandas中缺省值不参与计算 当使用df.min()等计算时,会发现缺省值不参与计算
代码示例
只可以用np.isnan判断array中是否包含np.nan
a = np. array( [ 1 , 2 , 3 , 4 , np. nan] )
a == np. nan
>> > array( [ False , False , False , False , False ] )
np. nan in a
>> > False
np. isnan( a)
>> > array( [ False , False , False , False , True ] )
a = np.array( [ 1,2 ,3,4,np.nan] )
a.max( )
>> > np.nan
a.min( )
>> > np.nan
b = np.array( [ 1 ,np.nan,3,4,5] )
a+b
>> > array( [ 2 ., nan, 6 ., 8 ., nan] )
np.isnan只可以对数值型array判断,当array中其余的元素为字符串是,array会将np.nan转换成’nan’ 在pandas中,np.nan和None都被视为缺省值
df = pd.DataFrame( { 'col1' :[ 'a' ,'b' ,'c' ,'d' ] , 'col2' :[ 1,2 ,3,4] } )
df.loc[ 1 ,'col1' ] = np.nan
df.loc[ 2 ,'col1' ] = None
df
>> > col1 col2
0 a 1
1 NaN 2
2 None 3
3 d 4
pd.isna( df)
>> > col1 col2
0 False False
1 True False
2 True False
3 False False
df = pd.DataFrame( np.arange( 8 ) .reshape( 2,4 ))
df.iloc[ 0,1 ] = None
df.iloc[ 0,2 ] = np.nan
df
>> > 0 1 2 3
0 0 NaN NaN 3
1 4 5.0 6.0 7
df.min( axis= 1 )
>> > 0 0.0
1 4.0
dtype: float64