使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变;
>>> a = np.array([1, 2, 3, 4]);b = np.array((5, 6, 7, 8));c = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]])
>>> b
array([5, 6, 7, 8])
>>> c
array([[ 1, 2, 3, 4],
[ 4, 5, 6, 7],
[ 7, 8, 9, 10]])
>>> c.dtype
dtype('int32')
>>> d = a.reshape((2,2))
>>> d
array([[1, 2],
[3, 4]])
>>> d = a.reshape((1,2))
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
d = a.reshape((1,2))
ValueError: total size of new array must be unchanged
>>> d = a.reshape((1,-1))
>>> d
array([[1, 2, 3, 4]])
>>> d = a.reshape((-1,1))
>>> d
array([[1],
[2],
[3],
[4]])
注意:a.reshape((1,-1))和a.reshape((1,2))和a.reshape((-1,1))