import numpy as np
转置(transpose)是重塑的一种形式,它返回的是源数据的视图(不会进行任何复制操作)。数组不仅有transpose方法,还有一个特殊的T属性:
In [3]:
arr = np.arange(15).reshape((3,5))arr
Out[3]:
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
In [4]:
arr.T
Out[4]:
array([[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]])
在进行矩阵计算时,经常需要用到该操作,比如利用np.dot计算矩阵內积:
In [22]:
arr = np.random.randn(6,3)np.dot(arr.T, arr)
Out[22]:
array([[ 3.94093877, -2.04846524, 0.68049782], [-2.04846524, 9.13085141, 1.46028225], [ 0.68049782, 1.46028225, 8.00914785]])
对于高维数组,transpose需要得到一个由轴编号组成的元组才能对这些轴进行转置(比较费脑子):
In [43]:
arr = np.arange(4).reshape((2,2))arr
Out[43]:
array([[0, 1], [2, 3]])
In [44]:
arr.transpose((0,1))
Out[44]:
array([[0, 1], [2, 3]])
In [48]:
np.transpose(arr)
Out[48]:
array([[0, 2], [1, 3]])
对于二维数组arr,我们看看它的每个元素:
In [50]:
arr[0][0]
Out[50]:
0
In [51]:
arr[0][1]
Out[51]:
1
In [52]:
arr[1][0]
Out[52]:
2
In [53]:
arr[1][1]
Out[53]:
3
我们来把第一个[]看作0轴,第二个[]看作是1轴,我们就比较好理解了:
In [56]:
# 0轴和1轴对换了arr.transpose((1,0))
Out[56]:
array([[0, 2], [1, 3]])
In [57]:
# 轴没有变化arr.transpose((0,1))
Out[57]:
array([[0, 1], [2, 3]])
对于三维数组:
![4385f4459fa8085af4d8d2443afe84e9.png](https://i-blog.csdnimg.cn/blog_migrate/0bd8a248fbf90b7da851e8ffdc949dcd.jpeg)
In [6]:
arr3d = np.arange(16).reshape(2,2,4)arr3d
Out[6]:
array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]]])
In [60]:
# 保持原来的轴顺序arr3d.transpose((0,1,2))
Out[60]:
array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]]])
In [61]:
# 交换0和2轴arr3d.transpose((2,1,0))
Out[61]:
array([[[ 0, 8], [ 4, 12]], [[ 1, 9], [ 5, 13]], [[ 2, 10], [ 6, 14]], [[ 3, 11], [ 7, 15]]])
In [62]:
# 交换1轴和2轴arr3d.transpose((0,2,1))
Out[62]:
array([[[ 0, 4], [ 1, 5], [ 2, 6], [ 3, 7]], [[ 8, 12], [ 9, 13], [10, 14], [11, 15]]])
In [7]:
# 交换0轴和1轴arr3d.transpose((1,0,2))
![941a75ad905c3dfa6b66031b97fad8f6.png](https://i-blog.csdnimg.cn/blog_migrate/e07e00b3a78b9af31a5fa20ff9b9cbfe.jpeg)
Out[7]:
array([[[ 0, 1, 2, 3], [ 8, 9, 10, 11]], [[ 4, 5, 6, 7], [12, 13, 14, 15]]])
简单的转置可以使用.T,它其实就是进行轴对换而已。ndarray还有一个swapaxes方法,它需要接受一对轴编号:
In [8]:
arr3d
Out[8]:
array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]]])
In [10]:
arr3d.swapaxes(1,2)
Out[10]:
array([[[ 0, 4], [ 1, 5], [ 2, 6], [ 3, 7]], [[ 8, 12], [ 9, 13], [10, 14], [11, 15]]])
可以看到结果和arr3d.transpose((0,2,1))是一样的。