0

I don't understand array as index in Python Numpy. For example, I have a 2d array A in Numpy

[[1,2,3]
 [4,5,6]
 [7,8,9]
 [10,11,12]]

What does A[[1,3], [0,1]] mean?

5
  • 3
    Have you tried, and studied the result? Commented Nov 6, 2017 at 4:59
  • or simply googled 'numpy indexing'? Commented Nov 6, 2017 at 5:00
  • I tried googling, but all tutorial are really long and I can't find out this exact syntax that I am looking for. Commented Nov 6, 2017 at 5:02
  • What exactly is it that you're looking for? Commented Nov 6, 2017 at 5:05
  • The answer is the exact thing I am looking for. I am trying to understand some code written by other people that has this syntax. Commented Nov 6, 2017 at 5:09

2 Answers 2

1

Just test it for yourself!

A = np.arange(12).reshape(4,3)
print(A)
>>> array([[ 0,  1,  2],
   [ 3,  4,  5],
   [ 6,  7,  8],
   [ 9, 10, 11]])

By slicing the array the way you did (docs to slicing), you'll get the first row, zero-th column element and the third row, first column element.

A[[1,3], [0,1]]
>>> array([ 3, 10])

I'd highly encourage you to play around with that a bit and have a look at the documentation and the examples.

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

1 Comment

Thank you so much for the explanation.
1

Your are creating a new array:

import numpy as np

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9],
     [10, 11, 12]]
A = np.array(A)

print(A[[1, 3], [0, 1]])
# [ 4 11]

See Indexing, Slicing and Iterating in the tutorial.

Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas

Quoting the doc:

def f(x,y):
    return 10*x+y

b = np.fromfunction(f, (5, 4), dtype=int)
print(b[2, 3])
# -> 23

You can also use a NumPy array as index of an array. See Index arrays in the doc.

NumPy arrays may be indexed with other arrays (or any other sequence- like object that can be converted to an array, such as lists, with the exception of tuples; see the end of this document for why this is). The use of index arrays ranges from simple, straightforward cases to complex, hard-to-understand cases. For all cases of index arrays, what is returned is a copy of the original data, not a view as one gets for slices.

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.