[Numpy-discussion] slicing an n-dimensional array

Jaime Fernández del Río jaime.frio at gmail.com
Wed Dec 3 20:41:35 EST 2014


On Wed, Dec 3, 2014 at 4:02 PM, Stefan van der Walt <stefan at sun.ac.za>
wrote:

> Hi Catherine
>
> On 2014-12-04 01:12:30, Moroney, Catherine M (398E) <
> Catherine.M.Moroney at jpl.nasa.gov> wrote:
> > I have an array "A" of shape (NX, NY, NZ), and then I have a second
> array "B" of shape (NX, NY)
> > that ranges from 0 to NZ in value.
> >
> > I want to create a third array "C" of shape (NX, NY) that holds the
> > "B"-th slice for each (NX, NY)
>
> Those two arrays can broadcast if you expand the dimensions of B:
>
> A: (NX, NY, NZ)
> B: (NX, NY, 1)
>
> Your result would be
>
> B = B[..., np.newaxis]  # now shape (NX, NY, 1)
> C = A[B]
>
> For more information on this type of broadcasting manipulation, see
>
>
> http://nbviewer.ipython.org/github/stefanv/teaching/blob/master/2014_assp_split_numpy/numpy_advanced.ipynb
>
> and
>
> http://wiki.scipy.org/EricsBroadcastingDoc
>
>
I don't think this would quite work... Even though it now has 3 dimensions
(Nx, Ny, 1), B is still a single array, so when fancy indexing A with it,
it will only be applied to the first axis, so the return will be of shape
B.shape + A.shape[1:], that is (Nx, Ny, 1, Ny, Nz).

What you need to have is three indexing arrays, one per dimension of A,
that together broadcast to the desired shape of the output C. For this
particular case, you could do:

nx = np.arange(A.shape[0])[:, np.newaxis]
ny = np.arange(A.shape[1])
C = A[nx, ny, B]

To show that this works:

>>> A = np.arange(2*3*4).reshape(2, 3, 4)
>>> A
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> B = np.random.randint(4, size=(2, 3))
>>> B
array([[2, 1, 2],
       [2, 0, 3]])
>>> nx = np.arange(A.shape[0])[:, None]
>>> ny = np.arange(A.shape[1])
>>> A[nx, ny, B]
array([[ 2,  5, 10],
       [14, 16, 23]])

Jaime

-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus planes
de dominación mundial.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141203/0ad2fa8b/attachment.html>


More information about the NumPy-Discussion mailing list