重组2D numpy数组通过2D行和列数组

huangapple go评论66阅读模式
英文:

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]])

huangapple
  • 本文由 发表于 2023年2月14日 18:47:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定