'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 .
Solution 1:[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.
Solution 2:[2]
The selected answer is not correct.
Here the
[2,0,1]indeed has shape(3,)and will not be extended during broadcasting.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]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jhon Doe |
| Solution 2 |
