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

2
  • What is your expected output? Commented Aug 20, 2017 at 19:40
  • I have no expectation about that. I wonder why it results so Commented Aug 20, 2017 at 19:42

2 Answers 2

4

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

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

2 Comments

is there a way to get a C or even fortran like array in python? The lists and othe rdata structure s seem very confusing especially combined with the strange scoping rules it seems to apply
Hi @user50619. Probably your question fits another thread better. Short answer is that numpy deals with C-like arrays under the hood, and you can orient the array C-like or Fortran-like. Please visit the doc for further details
1

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

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.