Numpy数组变形和轴变换
数组变形(reshape)或轴转换(Transposing Arrays and Swapping Axes)后返回的是非副本视图,对于非副本视图的修改会使原来的数组也同时改变。
In [1]: import numpy as np
#np.arange()产生一维数组
In [2]: arr = np.arange(15)
In [3]: arr
Out[3]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
#reshape((3,5))把数组转换成一个3*5的数组
In [4]: arr = arr.reshape((3,5))
In [5]: arr
Out[5]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
#.T实现数组转置
In [6]: arr.T
Out[6]:
array([[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]])
#np.dot实现矩阵点积
In [10]: np.dot(arr.T,arr)
Out[10]:
array([[125, 140, 155, 170, 185],
[140, 158, 176, 194, 212],
[155, 176, 197, 218, 239],
[170, 194, 218, 242, 266],
[185, 212, 239, 266, 293]])
#数组轴转换transpose 和 swapaxes内置方法使用
In [11]: arr = np.arange(16).reshape((2,2,4))
In [12]: arr
Out[12]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
#假设原始轴排序(0,1,2)为(x,y,z)
#arr.T相当arr.transpose((2,1,0)),相当于x与z轴调换位置成(z,y,x)
#例如原来元素5在(x=0,y=1,z=1)变换之后在(z=1,y=1,x=0)
In [13]: arr.T
Out[13]:
array([[[ 0, 8],
[ 4, 12]],
[[ 1, 9],
[ 5, 13]],
[[ 2, 10],
[ 6, 14]],
[[ 3, 11],
[ 7, 15]]])
In [14]: arr.transpose((2,1,0))
Out[14]:
array([[[ 0, 8],
[ 4, 12]],
[[ 1, 9],
[ 5, 13]],
[[ 2, 10],
[ 6, 14]],
[[ 3, 11],
[ 7, 15]]])
#arr.transpose((1,0,2)),相当于x与y轴调换位置成(y,x,z)
#例如原来元素5在(x=0,y=1,z=1)变换之后在(y=1,x=0,z=1)
In [15]: arr.transpose((1,0,2))
Out[15]:
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[ 4, 5, 6, 7],
[12, 13, 14, 15]]])
#arr.transpose((0,2,1)),相当于y与z轴调换位置成(x,z,y)
#例如原来元素6在(x=0,y=1,z=2)变换之后在(x=0,z=2,y=1)
In [16]: arr.transpose((0,2,1))
Out[16]:
array([[[ 0, 4],
[ 1, 5],
[ 2, 6],
[ 3, 7]],
[[ 8, 12],
[ 9, 13],
[10, 14],
[11, 15]]])
#arr.swapaxes(1,2)相当1和2轴变换,与arr.transpose((0,2,1))实现同一功能
In [17]: arr.swapaxes(1,2)
Out[17]:
array([[[ 0, 4],
[ 1, 5],
[ 2, 6],
[ 3, 7]],
[[ 8, 12],
[ 9, 13],
[10, 14],
[11, 15]]])
#数组变形或转换后返回的是非副本视图,对于非副本视图的修改会使原来的数组也同时改变。
#如arr.swapaxes(1,2)[0,1,1]原来是5,赋值等于10后,原来arr中的5也会变成10
In [20]: arr.swapaxes(1,2)[0,1,1] = 10
In [21]: arr
Out[21]:
array([[[ 0, 1, 2, 3],
[ 4, 10, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])