The total amount along the axis

Is there a numpy function to sum an array along (at most) a given axis? Along the axis, I mean something equivalent:

[x.sum() for x in arr.swapaxes(0,i)]. 

to sum along the i axis.

For example, the case where numpy.sum will not work directly:

 >>> a = np.arange(12).reshape((3,2,2)) >>> a array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]]]) >>> [x.sum() for x in a] # sum along axis 0 [6, 22, 38] >>> a.sum(axis=0) array([[12, 15], [18, 21]]) >>> a.sum(axis=1) array([[ 2, 4], [10, 12], [18, 20]]) >>> a.sum(axis=2) array([[ 1, 5], [ 9, 13], [17, 21]]) 
+6
source share
5 answers
 def sum_along_axis(a, axis=None): """Equivalent to [x.sum() for x in a.swapaxes(0,axis)]""" if axis is None: return a.sum() return np.fromiter((x.sum() for x in a.swapaxes(0,axis)), dtype=a.dtype) 
+2
source

Calling up the amount twice?

 In [1]: a.sum(axis=1).sum(axis=1) Out[1]: array([ 6, 22, 38]) 

Of course, it would be a little inconvenient to generalize, because the axes β€œdisappear”. Do you need this to be common?

 def sum_along(a, axis=0): js = [axis] + [i for i in range(len(a.shape)) if i != axis] a = a.transpose(js) while len(a.shape) > 1: a = a.sum(axis=1) return a 
+3
source

As for numpy 1.7.1, there is a simpler answer - you can pass a tuple into the argument "axis" of the sum method to sum over several axes. So, we summarize everything except this one:

 x.sum(tuple(j for j in xrange(x.ndim) if j!=i)) 
+3
source
 np.apply_over_axes(sum, a, [1,2]).ravel() 
+2
source

You can simply pass in the tuple with the axes you want to sum, and leave the one you want to β€œsum”:

 >> a.sum(axis=(1,2)) array([ 6, 22, 38]) 
+2
source

Source: https://habr.com/ru/post/895544/


All Articles