5

Let's say I have an numpy array A of size n x m x k and another array B of size n x m that has indices from 1 to k. I want to access each n x m slice of A using the index given at this place in B, giving me an array of size n x m.

Edit: that is apparently not what I want! [[ I can achieve this using take like this:

A.take(B) ]] end edit

Can this be achieved using fancy indexing? I would have thought A[B] would give the same result, but that results in an array of size n x m x m x k (which I don't really understand).

The reason I don't want to use take is that I want to be able to assign this portion something, like

A[B] = 1

The only working solution that I have so far is

A.reshape(-1, k)[np.arange(n * m), B.ravel()].reshape(n, m)

but surely there has to be an easier way?

Andreas Mueller
  • 27,470
  • 8
  • 62
  • 74

1 Answers1

3

Suppose

import numpy as np
np.random.seed(0)

n,m,k = 2,3,5
A = np.arange(n*m*k,0,-1).reshape((n,m,k))
print(A)
# [[[30 29 28 27 26]
#   [25 24 23 22 21]
#   [20 19 18 17 16]]

#  [[15 14 13 12 11]
#   [10  9  8  7  6]
#   [ 5  4  3  2  1]]]

B = np.random.randint(k, size=(n,m))
print(B)
# [[4 0 3]
#  [3 3 1]]

To create this array,

print(A.reshape(-1, k)[np.arange(n * m), B.ravel()])
# [26 25 17 12  7  4]

as a nxm array using fancy indexing:

i,j = np.ogrid[0:n, 0:m]
print(A[i, j, B])
# [[26 25 17]
#  [12  7  4]]
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677