Transpose and axis swap of ndarray arrays
Transpose resets the array, returning a view of the source data (without any copying).
There are three ways to transpose, transpose
method, T
property and swapaxes
method.
1 .T
import numpy as np
arr = np.arange(9).reshape((3,3))#生成一个3行3列的数组
print arr
[[0 1 2]
[3 4 5]
[6 7 8]]
print arr.T
[[0 3 6]
[1 4 7]
[2 5 8]]
2. transpose
For high-dimensional arrays, transpose requires a tuple of axis numbers to transpose.
For example, for a three-dimensional array, number the dimensions, that is, 0, 1, 2. Here 0,1,2 can be understood as the index of the returned tuple for shape.
for example
arr1 = np.arange(24).reshape(2,3,4)#生成一个2*3*4的数组
print arr1
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
print arr1.shape #看形状
(2, 3, 4) #说明这是一个2*3*4的数组(矩阵),返回的是一个元组,可以对元组进行索引,也就是0,1,2
transpose((1,0,2))
The meaning of is to (2, 3, 4)
convert into (3, 2, 4)
, for example, the index starting with the value 12 is [1,0,0]
, after the transformation, it becomes [0,1,0]
, as shown below:
print arr1.transpose((1,0,2))
[[[ 0 1 2 3]
[12 13 14 15]]
[[ 4 5 6 7]
[16 17 18 19]]
[[ 8 9 10 11]
[20 21 22 23]]]
3.swapages
swapaxes, which accept a pair of axis numbers. Swap shafts.
arr1 = np.arange(24).reshape(2,3,4)
print arr1
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
print arr1.swapaxes(1,0) #将第一个轴和第二个轴交换,对比transpose(1,0,2)
[[[ 0 1 2 3]
[12 13 14 15]]
[[ 4 5 6 7]
[16 17 18 19]]
[[ 8 9 10 11]
[20 21 22 23]]]