Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting from multidimensional numpy array

I have a multidimensional array a with shape (nt, nz, ny, nx). The dimensions are time, z, y, x. For each time, x and y, I've selected the appropriate z in a new index array J with shape (nt, ny, nx). J contains the indices along the height dimension that I'd like to select. Using Python, I could do this in a loop:

b=J.copy()
for t in range(nt):
   for y in range(ny):
      for x in range(nx):
         z=J[t,y,x]
         b[t,y,x]=a[t,z,y,x]

But I want to do this faster, without the loops. This is probably trivial, but I can't get my head around it. Anyone?

like image 388
erikwkolstad Avatar asked Feb 24 '23 11:02

erikwkolstad


1 Answers

You can use numpy.indices() together with advanced indexing:

t, y, x = numpy.indices(J.shape)
b = a[t, J, y, x]
like image 142
Sven Marnach Avatar answered Mar 07 '23 16:03

Sven Marnach