Detailed explanation of the axis and keepdim parameters of numpy's sum function

A.axis

axis is the specified axis.

A three-dimensional array can be regarded as a one-dimensional array whose elements are two-dimensional arrays, and a two-dimensional array can be regarded as a one-dimensional array whose elements are one-dimensional arrays. (It's comfortable to understand this way!)

Example:

axis=2 means that the three-dimensional array sums the innermost layer, that is, inside each one-dimensional array.

axis=0 is to sum the elements of the outermost layer.

Example stamp here

 

Two.keepdim

It can be understood that the'keepdims = True' parameter is to keep the dimension of the result the same as the original array, that is, keep dimension keeps the dimension.

import numpy as np


b=np.arange(12)
b=b.reshape(2,6)
print(b)
print('b中的元素之和:',np.sum(b))
#即在b的第一个轴上进行加和,相当于压缩行,也可以理解为二维矩阵的第一层括号里的东西加和
#若axis=1则是压缩列,也就是对第二层括号里面的进行求和
sum=np.sum(b,axis=0,keepdims=True)
print(sum)



operation result:

[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]
b中的元素之和: 66
[[ 6  8 10 12 14 16]]

The last output specifies axis=0, keepdim=True, you can see that the output is a two-dimensional array, if you don’t add keepdim=True, then the result is a one-dimensional array [6 8 10 12 14 16]

 

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/114636969