利用Python进行数据分析时,Numpy是最常用的库,经常用来对数组、矩阵等进行转置等,有时候用来做数据的存储。
在numpy中,转置transpose和轴对换是很基本的操作,下面分别详细讲述一下,以免自己忘记。
In [1]: import numpy as np In [2]: arr=np.arange(16).reshape(2,2,4) In [3]: arr Out[3]: array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]]])
如上图所示,将0-15放在一个2 2 4 的矩阵当中,得到结果如上。
现在要进行装置transpose操作,比如
In [4]: arr.transpose(1,0,2) Out[4]: array([[[ 0, 1, 2, 3], [ 8, 9, 10, 11]], [[ 4, 5, 6, 7], [12, 13, 14, 15]]])
结果是如何得到的呢?
每一个元素都分析一下,0位置在[0,0,0],转置为[1,0,2],相当于把原来位置在[0,1,2]的转置到[1,0,2],对0来说,位置转置后为[0,0,0],同理,对1 [0,0,1]来说,转置后为[0,0,1],同理我们写出所有如下:
其中第一列是值,第二列是转置前位置,第三列是转置后,看到转置后位置,再看如上的结果,是不是就豁然开朗了?
0 [0,0,0] [0,0,0]1 [0,0,1] [0,0,1]2 [0,0,2] [0,0,2]3 [0,0,3] [0,0,3]4 [0,1,0] [1,0,0]5 [0,1,1] [1,0,1]6 [0,1,2] [1,0,2]7 [0,1,3] [1,0,3]8 [1,0,0] [0,1,0]9 [1,0,1] [0,1,1]10 [1,0,2] [0,1,2]11 [1,0,3] [0,1,3]12 [1,1,0] [1,1,0]13 [1,1,1] [1,1,1]14 [1,1,2] [1,1,2]15 [1,1,3] [1,1,3]
再看另一个结果:
In [20]: arr.TOut[20]:array([[[ 0, 8], [ 4, 12]], [[ 1, 9], [ 5, 13]], [[ 2, 10], [ 6, 14]], [[ 3, 11], [ 7, 15]]])In [21]: arr.transpose(2,1,0)Out[21]:array([[[ 0, 8], [ 4, 12]], [[ 1, 9], [ 5, 13]], [[ 2, 10], [ 6, 14]], [[ 3, 11], [ 7, 15]]])
再对比转置前后的图看一下:
0 [0,0,0] [0,0,0] 1 [0,0,1] [1,0,0] 2 [0,0,2] [2,0,0] 3 [0,0,3] [3,0,0] 4 [0,1,0] [0,1,0] 5 [0,1,1] [1,1,0] 6 [0,1,2] [2,1,0] 7 [0,1,3] [3,1,0] 8 [1,0,0] [0,0,1] 9 [1,0,1] [1,0,1] 10 [1,0,2] [2,0,1] 11 [1,0,3] [3,0,1] 12 [1,1,0] [0,1,1] 13 [1,1,1] [1,1,1] 14 [1,1,2] [2,1,1] 15 [1,1,3] [3,1,1]
瞬间就明白转置了吧!其实只要动手写写,都很容易明白的。另外T其实就是把顺序全部颠倒过来,如下:
In [22]: arr3=np.arange(16).reshape(2,2,2,2)In [23]: arr3Out[23]:array([[[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]]], [[[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]])In [24]: arr3.TOut[24]:array([[[[ 0, 8], [ 4, 12]], [[ 2, 10], [ 6, 14]]], [[[ 1, 9], [ 5, 13]], [[ 3, 11], [ 7, 15]]]])In [25]: arr3.transpose(3,2,1,0)Out[25]:array([[[[ 0, 8], [ 4, 12]], [[ 2, 10], [ 6, 14]]], [[[ 1, 9], [ 5, 13]], [[ 3, 11], [ 7, 15]]]])
新闻热点
疑难解答