[Numpy-discussion] Operation over multiple axes? (Or: Partial flattening?)

Stéfan van der Walt stefan at sun.ac.za
Tue Jul 29 09:32:07 EDT 2008


2008/7/29 Hans Meine <meine at informatik.uni-hamburg.de>:
> with a multidimensional array (say, 4-dimensional), I often want to project
> this onto one single dimension, i.e.. let "dat" be a 4D array, I am
> interested in
>
>  dat.sum(0).sum(0).sum(0) # equals dat.sum(2).sum(1).sum(0)
>
> However, creating intermediate results looks more expensive than necessary; I
> would actually like to say
>
>  dat.sum((0,1,2))
>
> One way to achieve this is partial flattening, which I did like this:
>
>  dat.reshape((numpy.prod(dat.shape[:3]), dat.shape[3])).sum(0)
>
> Is there a more elegant way to do this?

That looks like a good way to do it.  You can clean it up ever so slightly:

x.reshape([-1, x.shape[-1]]).sum(axis=0)

Cheers
Stéfan



More information about the NumPy-Discussion mailing list