[Numpy-discussion] slicing an n-dimensional array
Stefan van der Walt
stefan at sun.ac.za
Wed Dec 3 19:02:21 EST 2014
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
Stéfan
More information about the NumPy-Discussion
mailing list