Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy sum along axis

Tags:

numpy

sum

axis

Is there a numpy function to sum an array along (not over) a given axis? By along an axis, I mean something equivalent to:

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

to sum along axis i.

For example, a 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]])
like image 812
user545424 Avatar asked Aug 21 '11 19:08

user545424


Video Answer


1 Answers

As of numpy 1.7.1 there is an easier answer here - you can pass a tuple to the "axis" argument of the sum method to sum over multiple axes. So to sum over all except the given one:

x.sum(tuple(j for j in xrange(x.ndim) if j!=i))
like image 61
JoeZuntz Avatar answered Nov 04 '22 01:11

JoeZuntz