YXD
YXD

Reputation: 32521

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

P = np.random.rand(M,N,2,9)

# index into the last dimension of P
indices = np.random.randint(0,9,size=(M,N))

# I'm after an array of shape (20,10,2)
# but this has shape (20, 10, 2, 20, 10)
P[...,indices].shape 

How can I correctly index P with indices to get an array of shape (20,10,2)?

If that's not too clear: For any i and j (in bounds) I want my_output[i,j,:] to be equal to P[i,j,:,indices[i,j]]

Upvotes: 4

Views: 484

Answers (1)

Jaime
Jaime

Reputation: 67507

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]

Upvotes: 2

Related Questions