感谢博主的启发:原博客链接
1、.T适用于一维、二维数组
In [1]: import numpy as np
In [2]: arr = np.arange(20).reshape(4,5) #生成一个4行5列的数组
In [3]: arr
Out[3]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
In [4]: arr.T #求转置
Out[4]:
array([[ 0, 5, 10, 15],
[ 1, 6, 11, 16],
[ 2, 7, 12, 17],
[ 3, 8, 13, 18],
[ 4, 9, 14, 19]])
2、numpy.transpose(a, axes=None)
Permute the dimensions of an array. 变更的数组的维度
Parameters:
a : 数组.
axes : list of ints, optional. By default, reverse the dimensions, otherwise permute the axes according to the values given.
Returns:
p : ndarray a with its axes permuted.
(注意:当对于一维、二维数组时,此方法与.T相似;其特点在于针对多维数组)
对于高维数组,transpose需要用到一个由轴编号组成的元组,才能进行转置。对多维数组来说,确定最底层的一个基本元素位置需要用到的索引个数即是维度
范例
# 二维数组的维度变换,等价于转置 .T
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.transpose(x)
array([[0, 2],
[1, 3]])
# 高维数组
>>> arr = np.arange(12).reshape(2,2,3)
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]])
arr1.shape #看形状
(2, 2, 3) #说明这是一个2*2*3的数组(矩阵),返回的是一个元组,可以对元组进行索引,也就是0,1,2
# 开始转置
>>> arr.transpose((1,0,2)) # 可见,轴0与轴1进行了位置变换,各个元素根据索引和shape进行变换
array([[[ 0, 1, 2],
[ 6, 7, 8]],
[[ 3, 4, 5],
[ 9, 10, 11]]])
# 解析:数值6开始的索引是[1,0,0],变换后变成了[0,1,0]
>>> arr.transpose((2,1,0))
[[[ 0 6]
[ 3 9]]
[[ 1 7]
[ 4 10]]
[[ 2 8]
[ 5 11]]]
# 解析:数值6开始的索引是[1,0,0],变换后变成了[0,0,1]
形状 | 索引 |
---|---|
2 | 0 |
2 | 1 |
3 | 2 |
transpose参数的真正意义在于这个shape元组的索引,它依赖于shape