0

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]]
1
  • What were you expecting? a[2,1] is an element, because it indexes both rows and columns. It can also be written as a[(2,1)]. Here the distinction between list and tuple is important. Commented Mar 13, 2022 at 22:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

So can I say that a[[1,2]] implicitly mean a[[1,2], :]?
@Rainning Yes, you're exactly right.
It's actually way more complicated than this. What you're seeing is a simple-looking special case of the rules for combining NumPy "basic indexing" and "advanced indexing". If you try to apply this logic to select a subset of rows and columns, you'll get surprising results or weird IndexErrors, because the simple-looking special case doesn't generalize like that.
@user2357112supportsMonica: Really thank you. My NumPy journey started from your comment two days ago. Now I understand both examples and something about advanced indexing.
To answer myself (i.e. the first comment) to make it a long story: a[[1,2]] actually means a[[1,2], :] (without the FutureWarning: ..., since 1d). And both indexes of a[[1,2],0], a[[1,2],1] got broadcast into shape (2,), and then the results stack along the second-axis(i.e. the number of columns increases).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.