虽然官网上关于reshape函数的标准格式是numpy.reshape(a, newshape, order='C'),但其实这个函数有两种用法。先看代码:
import numpy as npa=np.array([1,2,3,4,5,6,7,8,9,10,11,12])b=np.reshape(a,(2,-1))c=a.reshape(2,-1)print 'b='print bprint 'c='print c 结果:b=[[ 1 2 3 4 5 6] [ 7 8 9 10 11 12]]c=[[ 1 2 3 4 5 6] [ 7 8 9 10 11 12]] 可以看到,对数组a进行变换可以用b=np.reshape()或者c=a.reshape()的方式。
newshape参数: 用法参见以下代码: import numpy as npa=np.array([1,2,3,4,5,6,7,8,9,10,11,12])b=np.reshape(a,(2,-1))c=np.reshape(a,(2,2,-1))d=np.reshape(a,(2,3,-1))print 'b='print bprint 'c='print cprint 'd='print d 输出: b=[[ 1 2 3 4 5 6] [ 7 8 9 10 11 12]]c=[[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]]d=[[[ 1 2] [ 3 4] [ 5 6]] [[ 7 8] [ 9 10] [11 12]]] newshape参数用数组表示,以c为例,数组(2,2,-1)就是c的形状,一共有三阶,第三个数字是reshape后数组a中最小单元中元素个数,在这里是3,如果是-1则表示可以自动推测出。
order参数 是元素排列顺序的参数,一般不用。
2.shape函数 下面代码展示了该函数的用法:
c=np.array([1,2,3,4,5,6,7,8,9,10,11,12])c=c.reshape(2,3,2)print cprint c.shape输出:
[[[ 1 2] [ 3 4] [ 5 6]] [[ 7 8] [ 9 10] [11 12]]](2, 3, 2) 即得到sddyet的形状。