2
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 .

Jhon Doe
  • 113
  • 1
  • 11

2 Answers2

0

The selected answer is not correct.

  1. Here the [2,0,1] indeed has shape (3,) and will not be extended during broadcasting.

  2. While 1: means you first slicing the array before broadcasting. During the broadcasting, just think of the slicing : as a placeholder for a 0d-scalar at each run. So we get:

    shape([2,0,1]) = (3,)
    shape([:]) = () -> (1,) -> (3,)
    

    So it's the [:] conceptually extended into shape (3,), like this:

    x[[1,1,1], [2,0,1]] =
    [6 4 5]
    x[[2,2,2], [2,0,1]] =
    [10 8 9]
    

    Finally, we need to stack the results back

    [[6 4 5]
     [10  8  9]]
    
NeoZoom.lua
  • 2,269
  • 4
  • 30
  • 64
  • The current documentation explains that the basic and advanced indexing steps are (best viewed as) separate. `x[1:][:, [2, 0, 1]]` applies the slice first, and then the column selection after. Values would be the same if we reversed the order, though the strides differ. – hpaulj Mar 16 '22 at 20:16
-1

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.

Jhon Doe
  • 113
  • 1
  • 11
  • Updated link for mixing arrays and slices, https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing. The explanation is now longer and more detailed. – hpaulj Mar 16 '22 at 17:34
  • The equivalent is `x[[[1], [2]], [2, 0, 1]]`. At least the values are the same. The actual code is different, resulting in different `strides`, but that's a detail most of us don't have to worry about. – hpaulj Mar 16 '22 at 17:37