[Numpy-discussion] summing over more than one axis

Angus McMorland amcmorl@gmail....
Thu Aug 19 09:12:18 CDT 2010

```On 19 August 2010 10:01, greg whittier <gregwh@gmail.com> wrote:
> I frequently deal with 3D data and would like to sum (or find the
> mean, etc.) over the last two axes.  I.e. sum a[i,j,k] over j and k.
> I find using .sum() really convenient for 2d arrays but end up
> reshaping 2d arrays to do this.  I know there has to be a more
> convenient way.  Here's what I'm doing
>
> a = np.arange(27).reshape(3,3,3)
>
> # sum over axis 1 and 2
> result = a.reshape((a.shape[0], a.shape[1]*a.shape[2])).sum(axis=1)
>
> Is there a cleaner way to do this?  I'm sure I'm missing something obvious.

Another rank-generic approach is to use apply_over_axes (you get a
different shape to the result this way):

a = np.random.randint(20, size=(4,3,5))
b = np.apply_over_axes(np.sum, a, [1,2]).flat
assert( np.all( b == a.sum(axis=2).sum(axis=1) ) )

> Thanks,
> Greg
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>

--
AJC McMorland
Post-doctoral research fellow
Neurobiology, University of Pittsburgh
```