Numpy.array矩阵百分制化(比例化)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a19990412/article/details/90745159

简述

用途不用说,很常用

问题

  • 假设有数据A
>>> A
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

变成比例数如何操作?直接除以行求和?

>>> A / A.sum(axis=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,5) (4,)

解决办法

  • numpy一般来说,只做对应位的操作,或者是数值(其实理解为长度为一的向量会更加准确)和向量的操作。
  • 因此需要用np.newaxis操作来将numpy.array变成一样的shape
>>> A / A.sum(axis=1)[:, np.newaxis]
array([[0.        , 0.1       , 0.2       , 0.3       , 0.4       ],
       [0.14285714, 0.17142857, 0.2       , 0.22857143, 0.25714286],
       [0.16666667, 0.18333333, 0.2       , 0.21666667, 0.23333333],
       [0.17647059, 0.18823529, 0.2       , 0.21176471, 0.22352941]])
  • A.sum(axis=1)[:, np.newaxis] 是什么?就是复制了很多遍的向量而已
>>> A.sum(axis=1)
array([10, 35, 60, 85])
>>> A.sum(axis=1)[:, np.newaxis]
array([[10],
       [35],
       [60],
       [85]])

猜你喜欢

转载自blog.csdn.net/a19990412/article/details/90745159