参考资料:
- 黑马程序员相关教程
nan
-
两个nan是不相等的
print(np.nan == np.nan) # False
-
nan和任何值计算的结果均为nan
-
计算数组中nan的个数
t1 = np.array(range(12)).astype('float32').reshape((3, 4)) t1[1][2] = np.nan print(t1) # 方法一 print(np.count_nonzero(t1 != t1)) # 1 # 方法二 print(np.count_nonzero(np.isnan(t1))) # 1
-
nan的处理方法: 将nan的值用该行或该列的平均值代替
for i in range(t1.shape[0]): # 将nan用行平均值代替 temp_row = t1[i, :] # 获取当前行的数据 nan_num = np.count_nonzero(temp_row != temp_row) # 统计nan的个数 if nan_num != 0: temp_not_nan = temp_row[temp_row == temp_row] # 获取当前行中非nan的数据 temp_row[np.isnan(temp_row)] = temp_not_nan.mean() print(t1) # [[ 0. 1. 2. 3. ] # [ 4. 5. 5.3333335 7. ] # [ 8. 9. 10. 9. ]]
构造全0数组和全1数组
t = np.arange(12).reshape((3, 4))
print(t)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
t0 = np.zeros((t.shape[0], 1))
t1 = np.ones((t.shape[0], 1))
print(np.hstack((t0, t, t1)))
# [[ 0. 0. 1. 2. 3. 1.]
# [ 0. 4. 5. 6. 7. 1.]
# [ 0. 8. 9. 10. 11. 1.]]
创建一个单位矩阵
t1 = np.eye(5)
print(t1)
# [[1. 0. 0. 0. 0.]
# [0. 1. 0. 0. 0.]
# [0. 0. 1. 0. 0.]
# [0. 0. 0. 1. 0.]
# [0. 0. 0. 0. 1.]]
获取最大值和最小值的位置
t = np.arange(12).reshape(3, 4)
print(t.argmin(axis=0))
# [0 0 0 0]
print(t.argmax(axis=1))
# [3 3 3]
获取非0数据的位置
print(np.nonzero([1, 2, 0, 0, 4, 0]))
# (array([0, 1, 4], dtype=int64),)
数组填充
numpy.pad(array, pad_width, mode, **kwargs)
参数 | 解释 |
---|---|
array | 要填充的数组 |
pad_width | 表示每个轴需要填充的数值数目, 参数输入方式为((before0, after0), …, (beforeN,afterN)), 其中(before0, after0)表示第0轴两个边缘分别填充before0和after0个元素 |
mode | 填充方式, 常用’constant’, 默认填0 |
t = np.arange(12).reshape((3, 4))
t = np.pad(t, 1, 'constant')
print(t)
# [[ 0 0 0 0 0 0]
# [ 0 0 1 2 3 0]
# [ 0 4 5 6 7 0]
# [ 0 8 9 10 11 0]
# [ 0 0 0 0 0 0]]