0

I am not able to understand integer array indexing in numpy.

>>> x = np.array([[1, 2], [3, 4], [5, 6]])
>>> x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])

Please explain me what is happening in this?

1
  • From the docs for Indexing Multi-dimensional arrays "In this case, if the index arrays have a matching shape, and there is an index array for each dimension of the array being indexed, the resultant array has the same shape as the index arrays, and the values correspond to the index set for each position in the index arrays." Commented Feb 4, 2018 at 14:05

3 Answers 3

3
x[[0,1,2],[0,1,0]] 

[0,1,2] <- here you specify which arrays you will be using [0,1,0] <- here you choose elements from each of specified arrays

So element 0 from array 0, element 1 from array 1 and so on

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

Comments

1
In [76]: x = np.array([[1, 2], [3, 4], [5, 6]])
In [77]: x
Out[77]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

Because the 1st and 2nd indexing lists match in size, their values are paired up to select elements from x. I'll illustrate it with list indexing:

In [78]: x[[0, 1, 2], [0, 1, 0]]
Out[78]: array([1, 4, 5])
In [79]: list(zip([0, 1, 2], [0, 1, 0]))
Out[79]: [(0, 0), (1, 1), (2, 0)]
In [80]: [x[i,j] for i,j in zip([0, 1, 2], [0, 1, 0])]
Out[80]: [1, 4, 5]

Or more explicitly, it is returning x[0,0], x[1,1] and x[2,0], as a 1d array. Another way to think it is that you've picked the [0,1,0] elements from the 3 rows (respectively).

Comments

0

I find it easiest to understand as follows:

In [179]: x = np.array([[1, 2], [3, 4], [5, 6]])                                                                     

In [180]: x                                                                                                          
Out[180]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

Say we want to select 1, 4, and 5 from this matrix. So the 0th column of row 0, the 1st column of the 1st row, and the 0th column of the 2nd row. Now provide the index with two arrays (one for each dimension of the matrix), where we populate these arrays with the rows and then the columns we are interested in:

In [181]: rows = np.array([0, 1, 2])                                                                                 

In [182]: cols = np.array([0, 1, 0])                                                                                 

In [183]: x[rows, cols]                                                                                              
Out[183]: array([1, 4, 5])

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.