英文:
Rearranging 2D numpy array by 2D row and column arrays
问题
我尝试找到一个类似的问题,但到目前为止,只有我的问题的一半可以得到答案。
我有一个2D的numpy数组,例如:
a = np.array([[6, 4, 5],
[4, 7, 8],
[2, 8, 9]])
我还有另外两个numpy数组,指示我想要重新排列(或不重新排列)的行和列:
rows = np.array([[0, 0, 0],
[1, 0, 1],
[2, 2, 2]])
cols = np.array([[0, 1, 2],
[0, 0, 2],
[0, 1, 2]])
现在,我想根据这些索引重新排列数组 "a",使结果为:
result = np.array([[6, 4, 5],
[4, 6, 8],
[2, 8, 9]])
仅对行或仅对列进行此操作很容易,例如,请参考这个线程。
英文:
I have tried to find a similar question but so far it seems only half my question can be answered.
I have a 2D numpy array, e.g.:
a= np.array([[6, 4, 5],
[4, 7, 8],
[2, 8, 9]])
And i also have 2 further numpy arrays, indicating the rows, and columns where i would like to rearrange (or not):
rows= np.array([[0, 0, 0],
[1, 0, 1],
[2, 2, 2]])
cols= np.array([[0, 1, 2],
[0, 0, 2],
[0, 1, 2]])
now i would like to rearrange the array "a" based on these indices, so that the result is:
result= np.array([[6, 4, 5],
[4, 6, 8],
[2, 8, 9]])
Doing this only for columns or only for rows is easy, e.g. see this Thread:
np.array(list(map(lambda x, y: y[x], cols, a)))
答案1
得分: 2
这是一个典型的fancy/array indexing案例:
result = a[rows, cols]
输出:
array([[6, 4, 5],
[4, 6, 8],
[2, 8, 9]])
英文:
This is a typical case of fancy/array indexing:
result = a[rows, cols]
Output:
array([[6, 4, 5],
[4, 6, 8],
[2, 8, 9]])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论