cr001
cr001

Reputation: 663

Python Numpy syntax: what does array index as two arrays separated by comma mean?

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?

Upvotes: 0

Views: 360

Answers (2)

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22952

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.

Upvotes: 1

Daniel Lenz
Daniel Lenz

Reputation: 3857

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.

Upvotes: 1

Related Questions