What is a multidimensional way of placing a two-dimensional numpy array based on a 2D numpy index array?

import numpy as np
x = np.array([[1,2 ,3], [9,8,7]])
y = np.array([[2,1 ,0], [1,0,2]])

x[y]

Expected Result:

array([[3,2,1], [8,9,7]])

If x and y are 1D arrays, then x [y] will work. So what is the numpy way or the most pythonic or efficient way to do this for 2D arrays?

+4
source share
2 answers

You need to determine the corresponding row indices.

One of the methods:

>>> x[np.arange(x.shape[0])[..., None], y]
array([[3, 2, 1],
       [8, 9, 7]])
+2
source

You can calculate linear indices from y, and then use them to extract specific elements from x, for example:

# Linear indices from y, using x shape
lin_idx = y + np.arange(y.shape[0])[:,None]*x.shape[1]

# Use np.take to extract those indexed elements from x
out = np.take(x,lin_idx)

Run Example -

In [47]: x
Out[47]: 
array([[1, 2, 3],
       [9, 8, 7]])

In [48]: y
Out[48]: 
array([[2, 1, 0],
       [1, 0, 2]])

In [49]: lin_idx = y + np.arange(y.shape[0])[:,None]*x.shape[1]

In [50]: lin_idx  # Compare this with y
Out[50]: 
array([[2, 1, 0],
       [4, 3, 5]])

In [51]: np.take(x,lin_idx)
Out[51]: 
array([[3, 2, 1],
       [8, 9, 7]])
+1
source

All Articles