两个nan是不相等的
In [1]:import numpy as np
In [2]:np.nan != np.nan # 两个nan不想等,返回的是True
Out[2]: True
In [3]:np.nan = np.nan
In [4]:np.nan == np.nan # 两个nan想等,返回的是False
Out[4]: False
判断数组中不为0的数据的个数
In [5]:t = np.arange(24).reshape(4,6) # t赋值为4行6列的一个数组
In [6]:t
Out[6]:
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])
In [7]:t[:,0] = 0 # 将第一列赋值为0
In [8]:t
Out[8]:
array([[ 0, 1, 2, 3, 4, 5],
[ 0, 7, 8, 9, 10, 11],
[ 0, 13, 14, 15, 16, 17],
[ 0, 19, 20, 21, 22, 23]])
In [9]:np.count_nonzero(t) # 判断数组中不为0的数据的个数
Out[9]: 20
3. 判断数组中nan的个数,数组的计算
# 将t转换为float格式,因为nan是浮点型,将t中某些数据改为nan,必须将t转换为float
In [14]:t = t.astype(float)
In [16]:t[3,3:] = np.nan # 赋值为nan
In [17]:t
Out[17]:
array([[ 0., 1., 2., 3., 4., 5.],
[ 0., 7., 8., 9., 10., 11.],
[ 0., 13., 14., 15., 16., 17.],
[ 0., 19., 20., nan, nan, nan]])
In [19]:np.count_nonzero(t != t) # 方法1:判断nan的个数,t != t 即为nan,nan != nan
Out[19]: 3
In [20]:np.isnan(t) # np.isnan(t)和t != t效果一样,判断那些是nan的值
Out[20]:
array([[False, False, False, False, False, False],
[False, False, False, False, False, False],
[False, False, False, False, False, False],
[False, False, False, True, True, True]])
In [21]:np.count_nonzero(np.isnan(t)) # 方法2:判断nan的个数,np.isnan 即为nan
Out[21]: 3
# nan和任何值计算,结果都为nan
In [22]:np.sum(t)
Out[22]: nan
In [23]:np.sum(t,axis=0) # 列方向上值相加
Out[23]: array([ 0., 40., 44., nan, nan, nan])
In [24]: np.sum(t,axis=1) # 行方向上值相加
Out[34]: array([15., 45., 75., nan])