如何解决如何最有效地在一个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,0] -> [0,2,1] and all the rest are the the same
b=np.array(
[[[[0,0],1],2]],[[0,2]]],[[[1,[1,[[1,[[[2,[2,[[2,2]]]])
>>>np.something(a,b,whatever)
>>>np.array(
[[[ 3,[ 7,26]]])
我也很乐意让b在a的平展版本中充满索引,而不是坐标矢量,但是我仍然不确定它如何/是否可以有效地工作。
或者,如果有办法做到这一点,则可以使用如下的单位翻译对转换矩阵进行编码:
#the matrix to rearange
a=np.array(
[[[ 0,26]]])
#a transformation matric showing the same [0,but in terms of displacement.
#In other words,the data in [0,0] is moved down 2 rows and right 1 column to [0,because b[0,0]=[0,1]
b=np.array(
[[[[0,0]],-1,-1],0]]],[[[0,0]]]])
>>>np.something(a,whatever)
>>>np.array(
[[[ 3,26]]])
解决方法
(使用第一个"compilerOptions": {
}
和a
版本)您正在寻找
b
这会将a[tuple(np.moveaxis(b,-1,0))]
拆分为单独的数组,每个数组b
都一个,然后使用它们通过“高级”或“精美”索引将其索引到a
中。
请注意,a
转换在这里很重要。它通过告诉numpy将元组的每个元素都视为一维索引,从而改变了numpy解释索引的方式。如果将其保留为单个nd数组,则将其全部读入维度tuple
中。试试看吧!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。