Detailed Explanation of axis and keepdim Parameters of numpy's sum Function

  • 2021-10-11 18:52:52
  • OfStack

1.axis

axis is the designated axis.

A 3-D array can be thought of as a 1-D array whose elements are 2-D arrays, and a 2-D array can be thought of as a 1-D array whose elements are 1-D arrays. (It's comfortable to understand this!)

Example:

axis=2 means that the 3-D array sums the innermost layer, that is, the inside of each 1-D array.

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

Example poke here

2.keepdim

It can be understood that the parameter 'keepdims = True' is to keep the dimension of the result the same as that of 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 The sum of the elements in: ',np.sum(b))
# That is, in b The first part of 1 Adding on the axes is equivalent to compressing rows, which can also be understood as 2 The first of dimensional matrices 1 Add up the things in layer brackets 
# If axis=1 Is a compressed column, that is, for the first 2 Summation in layer brackets 
sum=np.sum(b,axis=0,keepdims=True)
print(sum)

Run results:

[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
Sum of Elements in b: 66
[[ 6 8 10 12 14 16]]
The last output specifies axis=0, keepdim=True, and you can see that the output is a 2-dimensional array. If you don't add keepdim=True, the result is a 1-dimensional array [6 8 10 12 14 16]


Related articles: