为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只甜甜圈 2023-08-08 17:41:28
我无法弄清楚如何有效地创建 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 sameb=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]]])
查看完整描述

1 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

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

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

这分成b单独的数组,每个数组对应一个维度,然后使用它们通过“高级”或“花式”索引a进行索引。a

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


查看完整回答
反对 回复 2023-08-08
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信