猿问

如何最有效地基于另一个 ndarray 切换一个 ndarray 中的元素

我无法弄清楚如何有效地创建 3d numpy 数组的副本,其中交换少量元素。


我希望能够执行以下操作:


#the matrix to rearange 

a=np.array(

 [[[ 0,  1,  2],

    [ 3,  4,  5],

    [ 6,  7,  8]],


   [[ 9, 10, 11],

    [12, 13, 14],

    [15, 16, 17]],


   [[18, 19, 20],

    [21, 22, 23],

    [24, 25, 26]]])


#a matric of indicies in a. In this case, [0,1,0] -> [0,0,0] -> [0,2,1] and all the rest are the the same

b=np.array(

[[[[0, 1, 0], [0, 0, 1], [0, 0, 2]],

  [[0, 2, 1], [0, 1, 1], [0, 1, 2]],

  [[0, 2, 0], [0, 0, 0], [0, 2, 2]]],


[[[1, 0, 0], [1, 0, 1], [1, 0, 2]],

 [[1, 1, 0], [1, 1, 1], [1, 1, 2]],

 [[1, 2, 0], [1, 2, 1], [1, 2, 2]]],


[[[2, 0, 0], [2, 0, 1], [2, 0, 2]],

 [[2, 1, 0], [2, 1, 1], [2, 1, 2]],

 [[2, 2, 0], [2, 2, 1], [2, 2, 2]]]])


>>>np.something(a,b,whatever)

>>>np.array(

 [[[ 3,  1,  2],

   [ 7,  4,  5],

   [ 6,  0,  8]],


   [[ 9, 10, 11],

    [12, 13, 14],

    [15, 16, 17]],


   [[18, 19, 20],

    [21, 22, 23],

    [24, 25, 26]]])

我也愿意让 b 在 a 的扁平版本中充满索引,而不是坐标向量,但我仍然不确定它如何/是否可以有效地工作。


或者,如果有一种方法可以实现此目的,则可以使用如下单位翻译对变换矩阵进行编码:


#the matrix to rearange 

a=np.array(

  [[[ 0,  1,  2],

    [ 3,  4,  5],

    [ 6,  7,  8]],


   [[ 9, 10, 11],

    [12, 13, 14],

    [15, 16, 17]],


   [[18, 19, 20],

    [21, 22, 23],

    [24, 25, 26]]])


 #a transformation matric showing the same [0,1,0] -> [0,0,0] -> [0,2,1], but in terms of displacement. 

#In other words, the data in [0,0,0] is moved down 2 rows and right 1 column to [0,2,0], because b[0,0,0]=[0,2,1]

b=np.array(

[[[[0, 2, 1], [0, 0, 0], [0, 0, 0]],

  [[0, -1, 0], [0, 0, 0], [0, 0, 0]],

  [[0, 0, 0], [0, -1, -1], [0, 0, 0]]],


 [[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

  [[0, 0, 0], [0, 0, 0], [0, 0, 0]],

  [[0, 0, 0], [0, 0, 0], [0, 0, 0]]],


 [[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

  [[0, 0, 0], [0, 0, 0], [0, 0, 0]],

  [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]])



>>>np.something(a,b,whatever)

>>>np.array(

  [[[ 3,  1,  2],

    [ 7,  4,  5],

    [ 6,  0,  8]],


   [[ 9, 10, 11],

    [12, 13, 14],

    [15, 16, 17]],


   [[18, 19, 20],

    [21, 22, 23],

    [24, 25, 26]]])


一只甜甜圈
浏览 115回答 1
1回答

元芳怎么了

(使用您的第一个版本a和b)您正在寻找a[tuple(np.moveaxis(b,-1,0))]这分成b单独的数组,每个数组对应一个维度,然后使用它们通过“高级”或“花式”索引a进行索引。a请注意,tuple这里的转换很重要。它通过告诉 numpy 将元组的每个元素视为一维索引来改变 numpy 解释索引的方式。保留为单个 nd 数组,而不是它会被读取为维度的所有索引0。尝试一下,感受一下!
随时随地看视频慕课网APP

相关分类

Python
我要回答