2

What is the fastest way of creating a new matrix that is a result of a "look-up" of some numpy matrix X (using an array of indices to be looked up in matrix X)? Example of what I want to achieve:

indices = np.array([[[1,1],[1,1],[3,3]],[[1,1],[5,8],[6,9]]]) #[i,j]
new_matrix = lookup(X, use=indices)

Output will be something like:

new_matrix = np.array([[3,3,7],[3,4,9]])

where for example X[1,1] was 3. I'm using python 2.

ru111
  • 813
  • 3
  • 13
  • 27

1 Answers1

1

Use sliced columns for indexing into X -

X[indices[...,0], indices[...,1]]

Or with tuple -

X[tuple(indices.T)].T # or X[tuple(indices.transpose(2,0,1))]

Sample run -

In [142]: X
Out[142]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 3, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 7, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 4, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 9]])

In [143]: indices
Out[143]: 
array([[[1, 1],
        [1, 1],
        [3, 3]],

       [[1, 1],
        [5, 8],
        [6, 9]]])

In [144]: X[indices[...,0], indices[...,1]]
Out[144]: 
array([[3, 3, 7],
       [3, 4, 9]])
Divakar
  • 218,885
  • 19
  • 262
  • 358