[SOLVED] Numpy Advanced Indexing : How the broadcast is happening?


array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

if we run the following statement

x[1:, [2,0,1]]

we get the following result

array([[ 6,  4,  5],
      [10,  8,  9]])

According to numpy’s doc:

Advanced indexes always are broadcast and iterated as one:

I am unable to understand how the pairing of indices is happening here and also broadcasting .


From NumPy User Guide, Section 3.4.7 Combining index arrays with slices

the slice is converted to an index array np.array that is broadcast
with the index array to produce the resultant array.

In our case the slice 1: is converted to to an index array np.array([[1,2]]) which has shape (1,2) . This is row index array.
The next index array ( column index array) np.array([2,0,1]) has shape (3,2)

  • row index array shape (1,2)
  • column index array shape (3,2)

the index arrays do not have the same shape. But they can be broadcasted to same shape. The row index array is broadcasted to match the shape of column index array.

Answered By – Jhon Doe

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *