假設我有一個3*3*3
陣列x
。我想找出一個陣列y
,這樣,這樣y[0,1,2] = x[1,2,0]
,或更一般地說,y[a,b,c]= x[b,c,a]
。我可以試試numpy.transpose
import numpy as np
x = np.arange(27).reshape((3,3,3))
y = np.transpose(x, [2,0,1])
print(x[0,1,2],x[1,2,0])
print(y[0,1,2])
輸出是
5 15
15
結果15,15
是我所期望的(第一個15
是來自 的參考值x[1,2,0]
;第二個是來自y[0,1,2]
)。但是,我[2,0,1]
通過在紙上繪圖找到了轉置。
B C A
A B C
通過檢查,轉置應該是[2,0,1]
,上排的最后一個條目到下排的第一個;中間最后一個;第一個去中間。是否有任何自動且希望有效的方法(如 numpy/sympy 中的任何標準函式)?
給定輸入y[a,b,c]= x[b,c,a]
,輸出[2,0,1]
?
uj5u.com熱心網友回復:
tranpose
我發現用一個形狀像 (2,3,4) 的例子來探索更容易,每個軸都是不同的。
但堅持你的 (3,3,3)
In [23]: x = np.arange(27).reshape(3,3,3)
In [24]: x
Out[24]:
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]]])
In [25]: x[0,1,2]
Out[25]: 5
您的樣本轉置:
In [26]: y = x.transpose(2,0,1)
In [27]: y
Out[27]:
array([[[ 0, 3, 6],
[ 9, 12, 15],
[18, 21, 24]],
[[ 1, 4, 7],
[10, 13, 16],
[19, 22, 25]],
[[ 2, 5, 8],
[11, 14, 17],
[20, 23, 26]]])
我們得到相同5
的
In [28]: y[2,0,1]
Out[28]: 5
我們可以通過應用相同的轉置值得到 (2,0,1):
In [31]: idx = np.array((0,1,2)) # use an array for ease of indexing
In [32]: idx[[2,0,1]]
Out[32]: array([2, 0, 1])
我對梯形 (2,0,1) 的看法是,我們將最后一個軸 2 移動到前面,并保留其他 2 的順序。
使用不同的維度,更容易可視化變化:
In [33]: z=np.arange(2*3*4).reshape(2,3,4)
In [34]: z
Out[34]:
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]]])
In [35]: z.transpose(2,0,1)
Out[35]:
array([[[ 0, 4, 8],
[12, 16, 20]],
[[ 1, 5, 9],
[13, 17, 21]],
[[ 2, 6, 10],
[14, 18, 22]],
[[ 3, 7, 11],
[15, 19, 23]]])
In [36]: _.shape
Out[36]: (4, 2, 3)
np.swapaxes
is another compiled function for making these changes. np.rollaxis
is another, though it's python code that ends up calling transpose
.
I haven't tried to follow all of your reasoning, though I think you want a kind reverse of the transpose
numbers, one where you specify the result order, and want how to get them.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424191.html