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]])
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With