numpy自学笔记__常用方法

参考资料:

  • 黑马程序员相关教程

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]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值