Gemini
Gemini

Reputation: 475

Use Array as Indexing Mask for Multidimensional Array

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?

Upvotes: 1

Views: 62

Answers (1)

Divakar
Divakar

Reputation: 221704

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

Upvotes: 1

Related Questions