numpy.sum

Parameters

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False)

  • a: numpy array
  • axis: If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
  • keepdims : bool, optional. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
  • return: An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned.

Explanation

You can consider a multi-dimensional array as a tensor, T[i][j][k] , while i,j,k represents axis 0,1,2 respectively.
T.sum(axis = 0) mathematically will be equivalent to: iTijk
Similarly, T.sum(axis = 1): jTijk
And, T.sum(axis = 2): kTijk

简单来说, axis 里面的维度在sum中会被删掉

Example

import numpy as np
>>> arr = np.arange(0,30).reshape(2,3,5)
>>> arr.shape
(2, 3, 5)

#the axis you sum along is removed from the shape
>>> arr.sum(axis=0).shape
(3, 5)  # the first entry (index = axis = 0) dimension was removed 
>>> arr.sum(axis=1).shape
(2, 5)  # the second entry (index = axis = 1) was removed

#You can also sum along multiple axis if you want (reducing the dimensionality by the amount of specified axis):
>>> arr.sum(axis=(0, 1))
array([75, 81, 87, 93, 99])
>>> arr.sum(axis=(0, 1)).shape
(5, )  # first and second entry is removed

#If you want to keep the dimensions you can specify keepdims:

>>> arr.sum(axis=0, keepdims=True)
array([[[15, 17, 19, 21, 23],
        [25, 27, 29, 31, 33],
        [35, 37, 39, 41, 43]]])

https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html
http://stackoverflow.com/questions/41733479/sum-along-axis-in-numpy-array

你可能感兴趣的:(python)