Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing one array by another in numpy

Tags:

Suppose I have a matrix A with some arbitrary values:

array([[ 2, 4, 5, 3],        [ 1, 6, 8, 9],        [ 8, 7, 0, 2]]) 

And a matrix B which contains indices of elements in A:

array([[0, 0, 1, 2],        [0, 3, 2, 1],        [3, 2, 1, 0]]) 

How do I select values from A pointed by B, i.e.:

A[B] = [[2, 2, 4, 5],         [1, 9, 8, 6],         [2, 0, 7, 8]] 
like image 367
voo Avatar asked Jun 17 '16 10:06

voo


People also ask

How do I connect two arrays in NumPy?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

How does NumPy array indexing work?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

What is NumPy fancy indexing?

Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.


1 Answers

EDIT: np.take_along_axis is a builtin function for this use case implemented since numpy 1.15. See @hpaulj 's answer below for how to use it.


You can use NumPy's advanced indexing -

A[np.arange(A.shape[0])[:,None],B] 

One can also use linear indexing -

m,n = A.shape out = np.take(A,B + n*np.arange(m)[:,None]) 

Sample run -

In [40]: A Out[40]:  array([[2, 4, 5, 3],        [1, 6, 8, 9],        [8, 7, 0, 2]])  In [41]: B Out[41]:  array([[0, 0, 1, 2],        [0, 3, 2, 1],        [3, 2, 1, 0]])  In [42]: A[np.arange(A.shape[0])[:,None],B] Out[42]:  array([[2, 2, 4, 5],        [1, 9, 8, 6],        [2, 0, 7, 8]])  In [43]: m,n = A.shape  In [44]: np.take(A,B + n*np.arange(m)[:,None]) Out[44]:  array([[2, 2, 4, 5],        [1, 9, 8, 6],        [2, 0, 7, 8]]) 
like image 147
Divakar Avatar answered Oct 05 '22 18:10

Divakar