Skip to content Skip to sidebar Skip to footer

Correctly Indexing A Multidimensional Numpy Array With Another Array Of Indices

I'm trying to index a multidimensional array P with another array indices. which specifies which element along the last axis I want, as follows: import numpy as np M, N = 20, 10

Solution 1:

I think this will work:

P[np.arange(M)[:, None, None], np.arange(N)[:, None], np.arange(2),
  indices[..., None]]

Not pretty, I know...


This may look nicer, but it may also be less legible:

P[np.ogrid[0:M, 0:N, 0:2]+[indices[..., None]]]

or perhaps better:

idx_tuple = tuple(np.ogrid[:M, :N, :2]) + (indices[..., None],)
P[idx_tuple]

Post a Comment for "Correctly Indexing A Multidimensional Numpy Array With Another Array Of Indices"