解疑 Numpy 中的 transpose

transpose

# 官方文档描述

numpy.ndarray.transpose

ndarray.transpose(*axes)
Returns a view of the array with axes transposed.

For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a matrix object.)  # transpose 对一维数组无效
For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).
# 对二维数组,其实就相当于矩阵的转置
Parameters: 
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a.transpose()‘s j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form)
Returns:    
out : ndarray
View of a, with axes suitably permuted.
See also
ndarray.T
Array property returning the array transposed.
Examples

>>>
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.transpose()
array([[1, 3],
       [2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
       [2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
       [2, 4]])

对于三维数组难理解一点:假设 shape(z, x, y)

shape 的 x轴 与 y 轴的转换比较简单, 跟二维数组一样

In [27]: arr.transpose((0, 2, 1))
Out[27]: 
array([[[ 0,  4],
        [ 1,  5],
        [ 2,  6],
        [ 3,  7]],

       [[ 8, 12],
        [ 9, 13],
        [10, 14],
        [11, 15]]])

对于 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 对应的值填进去 得到

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

so perfect 刚好对应输出

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值