4

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]]

2
  • I am probably being slow, but how can you use a 2D array to index along one axis ("the last axis" in your question)? Surely, indexing along a single axis requires one coordinate and not two? Commented Mar 27, 2013 at 14:09
  • I didn't explain it very well, which may well be related to why I am stuck here. For any i and j I want my_output[i,j,:] to be equal to P[i,j,:,indices[i,j]] Commented Mar 27, 2013 at 14:13

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.