我無法弄清楚如何有效地創建 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個贊
(使用您的第一個版本a
和b
)您正在尋找
a[tuple(np.moveaxis(b,-1,0))]
這分成b
單獨的數組,每個數組對應一個維度,然后使用它們通過“高級”或“花式”索引a
進行索引。a
請注意,tuple
這里的轉換很重要。它通過告訴 numpy 將元組的每個元素視為一維索引來改變 numpy 解釋索引的方式。保留為單個 nd 數組,而不是它會被讀取為維度的所有索引0
。嘗試一下,感受一下!
添加回答
舉報
0/150
提交
取消