# 云计算np.transpose用法解析

2018-01-10 11:43:26         来源：爱妃的博客

axis: int类型的列表，这个参数是可选的。默认情况下，反转的输入数组的维度，当给定这个参数时，按照这个参数所定的值进行数组变换。

```>>> import numpy as np
>>> t=np.arange(4)
>>> t
array([0, 1, 2, 3])
>>> t.transpose()
array([0, 1, 2, 3])
>>> ```

```>>> two=np.arange(16).reshape(4,4)
>>> two
array([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])
>>> two.transpose()
array([[ 0,  4,  8, 12],
[ 1,  5,  9, 13],
[ 2,  6, 10, 14],
[ 3,  7, 11, 15]])
>>> two.transpose(1,0)
array([[ 0,  4,  8, 12],
[ 1,  5,  9, 13],
[ 2,  6, 10, 14],
[ 3,  7, 11, 15]])```

```>>> three=np.arange(18).reshape(2,3,3)
>>> three
array([[[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8]],

[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]])
>>> three.transpose()
array([[[ 0,  9],
[ 3, 12],
[ 6, 15]],

[[ 1, 10],
[ 4, 13],
[ 7, 16]],

[[ 2, 11],
[ 5, 14],
[ 8, 17]]])
>>> ```

```#对原始three数组的下标写出来，如下：
A=[
[ [ (0,0,0) , (0,0,1) , (0,0,2)],
[ (0,1,0) , (0,1,1) , (0,1,2)],
[ (0,2,0) , (0,2,1) , (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)]]
]

#接着把上述每个三元组的第一个数和第三个数进行交换，得到以下的数组

B=[[[ (0,0,0) , (1,0,0) , (2,0,0)],
[ (0,1,0) , (1,1,0) , (2,1,0)],
[ (0,2,0) , (1,2,0) , (2,2,0)]],

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

#最后在原数组中把B对应的下标的元素，写到相应的位置
#对比看一下，这是原数组
[[[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8]],

[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]]
# 按照B的映射关系得到最终的数组。
C=[[[ 0,  9],
[ 3,  12],
[ 6,  15]],

[[ 1, 10],
[4, 13],
[7, 16]]

[[ 2, 11],
[5, 14],
[8, 17]]
]
# 最终的结果也就是数组C```

```import numpy as np
from PIL import Image
import os
data = np.empty((4, 20, 20), dtype="uint8")
imgs = os.listdir("E:\Kerasmnist/train\some")
num = len(imgs)
for i in range(num):
img = Image.open("E:\Kerasmnist/train\some/" + imgs[i])
img.show()
arr = np.asarray(img, dtype="uint8")
data[i, :, :] = arr

convert=data.transpose(2,1,0)

for k in range(len(convert[0])):
img2=Image.fromarray(convert[k])
img2.show()```