Home > Blockchain >  Why does indexing array with an array return two rows?
Why does indexing array with an array return two rows?

Time:03-14

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]]

CodePudding user response:

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".

  • Related