[Numpy-discussion] slicing an n-dimensional array

Moroney, Catherine M (398E) Catherine.M.Moroney at jpl.nasa.gov
Wed Dec 3 18:12:30 EST 2014


Hello,

I'm sure there's a simple solution, but I'm not seeing it so any hints would be
greatly appreciated.

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).

For example:

A = numpy.zeros((NX,NY,NZ))
A[:,:,0] = numpy.arange(0, NX*NY).reshape(NX,NY)
A[:,:,1] = numpy.arange(1, NX*NY+1).reshape(NX,NY)

and so on

B = numpy.zeros((NX,NY))
B[0,0] = 0
B[0,1] = 1

so C[0,0] = A[0,0,B[0,0]] 
   C[0,1] = A[0,1,B[0,1]] 
   ...
   C[NX-1,NY-1] = A[NX-1,NY-1,B[NX-1,NY-1]]

   and C has shape(NX,NY)

How do I accomplish this without loops?

Thank-you for any advice,

Catherine


More information about the NumPy-Discussion mailing list