Search code examples
pythonarraysnumpyindexingtake

Take elements of an array based on indexes in another array


I have an array of values on one side:

A = np.arange(30).reshape((3, 10))

Out: array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
            [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
            [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])

And an array of indexes referencing it where each column references each row in A.

np.random.seed(0)
index = np.random.randint(0, 9, 6).reshape((2, 3))

Out: array([[5, 0, 3],
            [3, 7, 3]])

I want to obtain an array of the same dimensions of the index array but replacing each index by its value in A. I have been able to accomplish by:

 np.dstack([A[0].take(index.T[0]),        
            A[1].take(index.T[1]),        
            A[2].take(index.T[2])]).squeeze()

Out: array([[ 5, 10, 23],
            [ 3, 17, 23]])

I believe I am missing something and this is not the optimal way to do it. I am also concerned on performance when the size of the arrays increases. Is there a more generic and scalable way to accomplish that?


Solution

  • You can use np.take_along_axis:

    np.take_along_axis(A, index.T, 1).T
    
    array([[ 5, 10, 23],
           [ 3, 17, 23]])