We have a main array called main_arr, and we want to transform it into another array called result with the same size, using a guide_arr, again with the same size:
import numpy as np
main_arr = np.array([[3, 7, 4], [2, 5, 6]])
guide_arr = np.array([[2, 0, 1], [0, 2, 1]])
result = np.zeros(main_arr.shape)
we need the result to equal to:
if np.array_equal(result, np.array([[7, 4, 3], [2, 6, 5]])):
print('success!')
How should we use guide_arr?
guide_arr[0,0] is 2, meaning that result[0,2] = main_arr[0,0]
guide_arr[0, 1] is 0 meaning that result[0, 0] = main_arr[0, 1]
guide_arr[0, 2] is 1 meaning that result[0, 1] = main_arr[0,2]
The same goes for row 1.
In summary, items in main_arr should be reordered (within a row, row never changes) so that their new column index equals the number in guide_arr.
The usual way of reordering columns, where the order differs by row, is with indexing like this:
The
arange(2)[:,None]
is a column array that broadcasts with the (2,3) index array.We can apply the same idea to using
guide_arr
to identify columns in theresult
:This may clarify how the broadcasting works: