我很难弄清楚如何高效地创建一个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]]])
(使用第一个版本的
a
和b
)您正在查找这会将
b
拆分为单独的数组,每个数组对应于a
的维度,然后使用它们通过“高级”或“高级”索引将其索引到a
请注意
tuple
转换在这里很重要。它改变了numpy解释索引的方式,告诉numpy将元组的每个元素视为一维索引。如果将其作为单个nd数组保留,则会将其作为所有索引读取到维度0
。试试看,感受一下相关问题 更多 >
编程相关推荐