根据另一个numpy数组整理numpy数组的每一行的列 [英] Reoder the columns of each row of a numpy array based on another numpy array
问题描述
我们有一个名为 main_arr 的主数组,我们想使用 guide_arr 将其转换为另一个具有相同大小的数组 result >, 再次使用相同的大小:
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)
我们需要等于的结果
if np.array_equal(result, np.array([[7, 4, 3], [2, 6, 5]])):
print('success!')
我们应该如何使用 guide_arr ?
guide_arr [0,0]为2,表示结果[0,2] = main_arr [0,0]
guide_arr[0,0] is 2, meaning that result[0,2] = main_arr[0,0]
guide_arr [0,1]为0表示结果[0,0] = main_arr [0,1]
guide_arr[0, 1] is 0 meaning that result[0, 0] = main_arr[0, 1]
guide_arr [0,2]为1表示结果[0,1] = main_arr [0,2]
guide_arr[0, 2] is 1 meaning that result[0, 1] = main_arr[0,2]
第1行也是如此.
总而言之,应该对main_arr中的项目重新排序(在一行中,行永远不会改变),以使它们的新列索引等于guide_arr中的编号.
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.
推荐答案
In [199]: main_arr = np.array([[3, 7, 4], [2, 5, 6]])
...: guide_arr = np.array([[2, 0, 1], [0, 2, 1]])
...:
按行对顺序进行排序的列的重新排序的通常方法是使用像这样的索引:
The usual way of reordering columns, where the order differs by row, is with indexing like this:
In [200]: main_arr[np.arange(2)[:,None],guide_arr]
Out[200]:
array([[4, 3, 7],
[2, 6, 5]])
arange(2)[:,None]
是一个列数组,它与(2,3)索引数组一起广播.
The arange(2)[:,None]
is a column array that broadcasts with the (2,3) index array.
我们可以将相同的想法应用于使用guide_arr
来标识result
中的列:
We can apply the same idea to using guide_arr
to identify columns in the result
:
In [201]: result = np.zeros_like(main_arr)
In [202]: result[np.arange(2)[:,None], guide_arr] = main_arr
In [203]: result
Out[203]:
array([[7, 4, 3],
[2, 6, 5]])
这可以阐明广播的工作方式:
This may clarify how the broadcasting works:
In [204]: np.broadcast_arrays(np.arange(2)[:,None], guide_arr)
Out[204]:
[array([[0, 0, 0],
[1, 1, 1]]),
array([[2, 0, 1],
[0, 2, 1]])]
这篇关于根据另一个numpy数组整理numpy数组的每一行的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!