开发者

numpy sum along axis

开发者 https://www.devze.com 2023-03-29 11:06 出处:网络
Is there a numpy function to sum an array along (not over) a given axis开发者_C百科? By along an axis, I mean something equivalent to:

Is there a numpy function to sum an array along (not over) a given axis开发者_C百科? 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]])


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


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


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


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)


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

精彩评论

暂无评论...
验证码 换一张
取 消