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

2024-09-28 03:19:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难弄清楚如何高效地创建一个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]]])

Tags: andofthetoinnumpynparray
1条回答
网友
1楼 · 发布于 2024-09-28 03:19:15

(使用第一个版本的ab)您正在查找

a[tuple(np.moveaxis(b,-1,0))]

这会将b拆分为单独的数组,每个数组对应于a的维度,然后使用它们通过“高级”或“高级”索引将其索引到a

请注意tuple转换在这里很重要。它改变了numpy解释索引的方式,告诉numpy将元组的每个元素视为一维索引。如果将其作为单个nd数组保留,则会将其作为所有索引读取到维度0。试试看,感受一下

相关问题 更多 >

    热门问题