我们给出例子,来看看 transpose( ) 函数是如何应用在矩阵转置操作中的。
- # numpy.transpose() 转置操作
- import numpy as np
- a = np.arange(12).reshape(3, 4)
- print('原数组:\n{},原数组的尺寸:{}\n'.format(a, a.shape))
- print('转置数组:\n{},转置数组的尺寸:{}\n'.format(np.transpose(a), np.transpose(a).shape))
打印结果:
- 原数组:
- [[ 0 1 2 3]
- [ 4 5 6 7]
- [ 8 9 10 11]],原数组的尺寸:(3, 4)
-
- 转置数组:
- [[ 0 4 8]
- [ 1 5 9]
- [ 2 6 10]
- [ 3 7 11]],转置数组的尺寸:(4, 3)
transpose() 也可以用于numpy中高维度数组的轴变换,以三维数组来举例:transpose()括号中传入的参数通常为0,1,2,可以将0看作0轴,1看作1轴,2看作2轴。 transpose的括号中的参数代表的就是数组的维度。transpose(0,1,2) 表示三个维度不发生交换,还是原来的数组;transpose(1,0,2) 表示第0维度和第1维度发生交换。
使用方法
初始化一个 shape 为 (2, 3, 4) 的高维数组,如下代码所示:
- import numpy as np
- arr = np.arange(0, 24).reshape(2, 3, 4)
- print(arr.shape) # shape:(2, 3, 4)
方法1:
- arr0_1_2 = arr.transpose(0, 1, 2)
- arr1_0_2 = arr.transpose(1, 0, 2)
- print(arr0_1_2.shape) # shape:(2, 3, 4)
- print(arr1_0_2.shape) # shape:(3, 2, 4)
我们看到,在对原数组 arr 进行transpose(0, 1, 2) 操作之后得到一个新的数组arr0_1_2,arr0_1_2 的 shape 与 arr 的 shape一致;而对原数组 arr 进行transpose(1, 0, 2) 操作之后得到的数组arr1_0_2 的 shape 与 arr 的 shape不一致,arr1_0_2的shape为 (3, 2, 4)。
方法2:
- # 方法2
- arr0_1_2 = np.transpose(arr, (0, 1, 2))
- arr1_0_2 = np.transpose(arr, (1, 0, 2))
- print(arr0_1_2.shape) # shape:(2, 3, 4)
- print(arr1_0_2.shape) # shape:(3, 2, 4)
我们把原数组arr的每一个值打印出来,如下所示。
- print('原数组:\n{},原数组的尺寸:{}\n'.format(arr, arr.shape))
- print('转置数组:\n{},转置数组的尺寸:{}\n'.format(arr.transpose(1, 0, 2), arr.transpose(1, 0, 2).shape))
- 原数组:
- [[[ 0 1 2 3]
- [ 4 5 6 7]
- [ 8 9 10 11]]
-
- [[12 13 14 15]
- [16 17 18 19]
- [20 21 22 23]]],原数组的尺寸:(2, 3, 4)
-
- 转置数组:
- [[[ 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, 2, 4)