# [Numpy-discussion] selecting all 2-d slices out of n-dimensional array

Robert Kern robert.kern at gmail.com
Tue Aug 29 21:47:21 EDT 2017

On Tue, Aug 29, 2017 at 6:03 PM, Moroney, Catherine M (398E) <
Catherine.M.Moroney at jpl.nasa.gov> wrote:

> Hello,
>
>
>
> I have an n-dimensional array (say (4,4,2,2)) and I wish to automatically
> extract all the (4,4) slices in it.
>
> i.e.
>
>
>
> a = numpy.arange(0, 64).reshape(4,4,2,2)
>
> slice1 = a[..., 0, 0]
>
> slice2 = a[..., 0, 1]
>
> slice3 = a[..., 1, 0]
>
> slice4 = a[..., 1,1]
>
>
>
> Simple enough example but in my case array “a” will have unknown rank and
> size.  All I know is that it will have more than 2 dimensions, but I don’t
> know ahead of time how many dimensions or what the size of those dimensions
> are.
>
>
>
> What is the best way of tackling this problem without writing a whole
> bunch of if-then cases depending on what the rank and shape of a is?  Is
> there a one-size-fits-all solution?
>

First, reshape the array to (4, 4, -1). The -1 tells the method to choose
whatever's needed to get the size to work out. Then roll the last axis to
the front, and then you have a sequence of the (4, 4) arrays that you
wanted.

E.g. (using (4,4,3,3) as the original shape for clarity)

[~]
|26> a = numpy.arange(0, 4*4*3*3).reshape(4,4,3,3)

[~]
|27> b = a.reshape([4, 4, -1])

[~]
|28> b.shape
(4, 4, 9)

[~]
|29> c = np.rollaxis(b, -1, 0)

[~]
|30> c.shape
(9, 4, 4)

[~]
|31> c[0]
array([[  0,   9,  18,  27],
[ 36,  45,  54,  63],
[ 72,  81,  90,  99],
[108, 117, 126, 135]])

[~]
|32> c[1]
array([[  1,  10,  19,  28],
[ 37,  46,  55,  64],
[ 73,  82,  91, 100],
[109, 118, 127, 136]])

--
Robert Kern
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20170829/d3520bf6/attachment-0001.html>