1

I have the following arrays:

a = np.arange(12).reshape((2, 2, 3))

and

b = np.zeros((2, 2))

Now I want to use b to access a, s.t. at each for index i,j we take the z-th element of a, if b[i, j] = z. Meaning for the above example the answer should be [[0, 3], [6, 9]]. I feel this is very related to np.choose, but yet somehow cannot quite manage it. Can you help me?

1
  • yes thank you. could you just add a few more details on your solution? e.g. why do i need [:, None] for the first indices? Commented Apr 11, 2019 at 10:07

1 Answer 1

1

Two approaches could be suggested.

With explicit range arrays for advanced-indexing -

m,n = b.shape
out = a[np.arange(m)[:,None],np.arange(n),b.astype(int)]

With np.take_along_axis -

np.take_along_axis(a,b.astype(int)[...,None],axis=2)[...,0]

Sample run -

In [44]: a
Out[44]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

In [45]: b
Out[45]: 
array([[0., 0.],
       [0., 0.]])

In [46]: m,n = b.shape

In [47]: a[np.arange(m)[:,None],np.arange(n),b.astype(int)]
Out[47]: 
array([[0, 3],
       [6, 9]])

In [48]: np.take_along_axis(a,b.astype(int)[...,None],axis=2)[...,0]
Out[48]: 
array([[0, 3],
       [6, 9]])
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.