4

Say I have an array

A = array([[1,2,3],
           [4,5,6],
           [7,8,9]])

Index array is

B = array([[1], # want [0, 1] element of A
           [0],  # want [1, 0], element of A
           [1]])  # want [2, 1] elemtn of A

By this index array B, I want a 3-by-1 array, whose elements are taken from array A, that is

C = array([[2],
           [4],
           [8]])

I tried numpy.choose, but I failed to that.

3 Answers 3

5

For answer completeness... Fancy indexing arrays are broadcast to a common shape, so the following also works, and spares you that final reshape:

>>> A[np.arange(3)[:, None], B]
array([[2],
       [4],
       [8]])
Sign up to request clarification or add additional context in comments.

Comments

3

You can do something like this:

>>> A[np.arange(len(A)), B.ravel()].reshape(B.shape)
array([[2],
       [4],
       [8]])

1 Comment

Nice, why didn't I think of it, ;-)
2

You can do:

>>>np.diag(A[range(3),B]).reshape(B.shape)
array([[2],
       [4],
       [8]])

If you want to use choose you can do: np.choose(B.ravel(), A.T).reshape(B.shape).

1 Comment

Thanks for the trick, the doc of choose is hard for me to understand.

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.