import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
I don't understand why it results [1 4 5] and [2 2]
-
What is your expected output?Adi219– Adi2192017年08月20日 19:40:39 +00:00Commented Aug 20, 2017 at 19:40
-
I have no expectation about that. I wonder why it results soBETUL– BETUL2017年08月20日 19:42:56 +00:00Commented Aug 20, 2017 at 19:42
2 Answers 2
Because you're slicing the array with indexes
a[[0, 1, 2], [0, 1, 0]] is equivalent to
a[0, 0] # 1
a[1, 1] # 4
a[2, 0] # 5
whereas a[[0, 0], [1, 1]] is equivalent to twice a[0, 1]
More about Numpy indexing here
2 Comments
Think of it as 2d-array access. When you initialize a you get your 2d array in the form:
[ 1 2 ]
[ 3 4 ]
[ 5 6 ]
Numpy indexing when given a 2d array works as follows: you input a list of the row indexes, then a list of the column indexes. Semantically your first index retrieval statement is saying "from row 0 retrieve element 0, from row 1 retrieve element 1, and from row 2 retrieve element 0" which corresponds to [1 4 5]. You can then figure out why you get [2 2] for the second statement.
You can read more about this advanced indexing here: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing
Comments
Explore related questions
See similar questions with these tags.