解疑 Numpy 中的 transpose(转置)和swapaxes(两个轴转置变换)

1.一维和二维数据

.T等同于.transopse

2.三维及更多维数据

对于 z 轴 与 x 轴的变换

In [40]: arr = np.arange(16).reshape((2, 2, 4))

In [41]: arr
Out[41]: 
array([[[ 0,  1,  2,  3],   
        [ 4,  5,  6,  7]],  
       [[ 8,  9, 10, 11],   
        [12, 13, 14, 15]]]) 

In [42]: arr.transpose((1, 0, 2))
Out[42]: 
array([[[ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],
       [[ 4,  5,  6,  7],
        [12, 13, 14, 15]]])

transpose 的变换是根据 shape 进行的

转换前 shape 是(0, 1, 2)

[[(0,0,0), (0,0,1), (0,0,2), (0,0,3)] // [[[ 0, 1, 2, 3], 
[(0,1,0), (0,1,1), (0,1,2), (0,1,3)], // [ 4, 5, 6, 7]], 
[(1,0,0), (1,0,1), (1,0,2), (1,0,3)] // [[ 8, 9, 10, 11], 
[(1,1,0), (1,1,1), (1,1,2), (1,1,3)]]. //[12, 13, 14, 15]]]

转换后 shape 是(1, 0, 2), 也就是调换位于 z 轴 和 x 轴的shape

[[(0,0,0), (0,0,1), (0,0,2), (0,0,3)] 
(1,0,0), (1,0,1), (1,0,2), (1,0,3)], 
[(0,1,0), (0,1,1), (0,1,2), (0,1,3)] 
[(1,1,0), (1,1,1), (1,1,2), (1,1,3)]]

将转换前 shape 对应的值填进去 得到

[0,1,2,3]
[8,9,10,11]
[4,5,6,7]
[12,13,14,15]

so perfect 刚好对应输出

3.swapaxes(两个轴转置变换)

In [4]: arr2.swapaxes(1,0)#转置,=transpose(1,0,2)
Out[4]:
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[ 4, 5, 6, 7],
[12, 13, 14, 15]]])

 

posted @ 2018-05-07 11:05  fanrupin  阅读(290)  评论(0编辑  收藏  举报