9

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]])
1

5 Answers 5

7

You can just pass a tuple with the axes that you want to sum over, and leave out the one that you want to 'sum along':

>> a.sum(axis=(1,2))
array([ 6, 22, 38])
Sign up to request clarification or add additional context in comments.

Comments

4

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))

Comments

3

Call sum twice?

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

Of course, this would be a little awkward to generalize because axes "disappear". Do you need it to be general?

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

Comments

2
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)

Comments

2
np.apply_over_axes(sum, a, [1,2]).ravel()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.