[SOLVED] Why does indexing array with an array return two rows?

Issue

I’m learning some basic of indexing in numpy. I don’t understand why

a = np.array([[1,2], [3,4], [5,6]])
b = a[[1,2]]

pprint(b)

gives

[[3 4]
 [5 6]]

Solution

a[[1, 2]] specifies to return the second (index 1) and third (index 2) rows of the array.

[1, 2] is the indexer. If you wanted to get the first (index 0) column of the array, you would use a similar indexer, only passing it to the second position:

>>> a[:, [0]]
array([[1],
       [3],
       [5]])

The : basically means "just select all the rows", and [0] means "select the 0th column".

Answered By – richardec

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *