Numpy fancy indexing with 2D array – explanation

Question:

I am (re)building up my knowledge of numpy, having used it a little while ago.
I have a question about fancy indexing with multidimenional (in this case 2D) arrays.

Given the following snippet:

>>> a = np.arange(12).reshape(3,4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> i = np.array( [ [0,1],                        # indices for the first dim of a
...                 [1,2] ] )
>>> j = np.array( [ [2,1],                        # indices for the second dim
...                 [3,3] ] )
>>>
>>> a[i,j]                                     # i and j must have equal shape
array([[ 2,  5],
       [ 7, 11]])

Could someone explain in simple English, the logic being applied to give the results produced. Ideally, the explanation would be applicable for 3D and higher rank arrays being used to index an array.

Conceptually (in terms of restrictions placed on “rows” and “columns”), what does it mean to index using a 2D array?

Answers:

Conceptually (in terms of restrictions placed on “rows” and “columns”), what does it mean to index using a 2D array?

It means you are constructing a 2d array R, such that R=A[B, C]. This means that the value for rij=abijcij.

So it means that the item located at R[0,0] is the item in A with as row index B[0,0] and as column index C[0,0]. The item R[0,1] is the item in A with row index B[0,1] and as column index C[0,1], etc.


So in this specific case:

>>> b = a[i,j]
>>> b
array([[ 2,  5],
       [ 7, 11]])

b[0,0] = 2 since i[0,0] = 0, and j[0,0] = 2, and thus a[0,2] = 2. b[0,1] = 5 since i[0,0] = 1, and j[0,0] = 1, and thus a[1,1] = 5. b[1,0] = 7 since i[0,0] = 1, and j[0,0] = 3, and thus a[1,3] = 7. b[1,1] = 11 since i[0,0] = 2, and j[0,0] = 3, and thus a[2,3] = 11.

So you can say that i will determine the “row indices”, and j will determine the “column indices”. Of course this concept holds in more dimensions as well: the first “indexer” thus determines the indices in the first index, the second “indexer” the indices in the second index, and so on.

Answered By: Willem Van Onsem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.