python—transpose( ) 处理高维度数组的轴变换

矩阵的转置操作

        我们给出例子,来看看 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高维度数组轴变换

        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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值