Donovan Thomson
Donovan Thomson

Reputation: 2525

Indexing with Numpy is inverted

I am busy reading through Python for Data Analysis by Wes Mckinney and I have encountered the following example which is slightly confusing. It pertains to passing multiple index arrays to an np array.

Given the following np.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 30 31]] 

when we execute fancy indexing on the array using the following values

arr[[1, 5, 7, 2], [0, 3, 1, 2]]

the following results

array([ 4, 23, 29, 10]) 

This is not really what I would expect> I understand that it should return a 1 d array of elements corresponding to each tupple of instances. The actual values it is returning confuses me.

The tuples it should be returning in my opinion would be (0,1), (5,3), (7, 1), (2, 2)

which should return [4, no such element, no such element, 10]

What exactly am I missing ?

Upvotes: 4

Views: 1379

Answers (1)

unutbu
unutbu

Reputation: 879251

When you index the first element in a 2D array, arr, you get the first row:

In [119]: arr = np.array([[0,1,2],[3,4,5]])

In [120]: arr
Out[120]: 
array([[0, 1, 2],
       [3, 4, 5]])

In [123]: arr[0]
Out[123]: array([0, 1, 2])

In NumPy-lingo, the "0-axis" therefore is associated with the rows of arr. Notice also the close association between arr and the list of lists

In [126]: lol = [[0,1,2],[3,4,5]]

In [127]: lol[0]
Out[127]: [0, 1, 2]

Surely, for a list of lists, it makes perfect sense that lol[0] should return the first item, which is [0, 1, 2]. arr[0] behaves the same way -- it returns what looks like a row.

Similarly, if you slice along the second axis you get a column.

In [125]: arr[:, 0]
Out[125]: array([0, 3])

In general, the order of the indices matches the order of the axes. The 0-axis first, the 1-axis second, and so on.

So in a 2D array, the 0-axis is associated with the rows, and the 1-axis is associated with the columns.

This might seem backwards to you if you are thinking about the elements of the array being arranged along x and y axes. In geometry, the x-axis is usually pointing to the right, and the y-axis is vertical. So in geometry the coordinate (x, y) gives the horizontal index first, then the vertical index.

When indexing arrays, the association is reversed for the reason shown above.

Upvotes: 5

Related Questions