[Numpy-discussion] summing over more than one axis
Thu Aug 19 09:06:32 CDT 2010
On Thu, Aug 19, 2010 at 9:01 AM, greg whittier <firstname.lastname@example.org> 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, a.shape*a.shape)).sum(axis=1)
> Is there a cleaner way to do this? I'm sure I'm missing something obvious.
Using two sums
np.sum(np.sum(a, axis=-2), axis=1)
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion