【问题标题】:How to most efficiently switch around elements in one ndarray based on another ndarray如何基于另一个 ndarray 最有效地切换一个 ndarray 中的元素
【发布时间】:2020-09-16 04:13:09
【问题描述】:

我无法弄清楚如何有效地创建一个 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]]])

【问题讨论】:

  • 你能解释一下b 数组中的值应该如何交换a 数组中元素的位置吗?
  • 您在寻找基本的精美索引吗?
  • 为了清楚起见,我添加了 cmets。花式索引可以像这样在 3d 中工作吗?

标签: python numpy numpy-ndarray


【解决方案1】:

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

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

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

请注意,tuple 转换在这里很重要。它通过告诉 numpy 将元组的每个元素视为对一维的索引来改变 numpy 解释索引的方式。保留为单个 nd 数组,而不是将其读取为所有索引到维度 0。试一试感受一下吧!

【讨论】:

    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 2021-03-14
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多