在不更改数据的情况下为数组赋予新的形状。
参数:a: : array_like
要重塑的数组。
newshape: : int 或 tuple of ints
新形状应与原始形状兼容。如果是整数,则结果将是该长度的一维数组。一种形状尺寸可以为-1。在这种情况下,该值是根据数组的长度和其余维来推断的。
order: : {‘C’, ‘F’, ‘A’}, 可选参数
使用此索引顺序读取a的元素,并使用此索引顺序将元素放入重新排列的数组中。 ‘C’表示使用C-like索引顺序读取/写入元素,最后一个轴索引更改最快,回到第一个轴索引更改最快。 ‘F’表示使用Fortran-like索引顺序读取/写入元素,第一个索引变化最快,最后一个索引变化最慢。请注意,‘C’和‘F’选项不考虑基础数组的内存布局,仅参考索引的顺序。 ‘A’表示如果a在内存中是连续的,则按Fortran-like索引顺序读取/写入元素,否则为C-like顺序。
返回值:reshaped_array: : ndarray
如果可能的话,这将是一个新的视图对象。否则,它将是副本。注意,不能保证返回数组的内存布局(C或Fortran连续)。
注意:
在不复制数据的情况下,并非总是可以更改数组的形状。如果希望在复制数据时引发错误,则应将新形状分配给数组的shape属性:
>>> a = np.zeros((10, 2))
# A transpose makes the array non-contiguous
>>> b = a.T
# Taking a view makes it possible to modify the shape without modifying
# the initial object.
>>> c = b.view()
>>> c.shape = (20)
Traceback (most recent call last):
...
AttributeError:incompatible shape for a non-contiguous array
order关键字给出索引排序,以用于从a取值,然后将值放入输出数组。例如,假设您有一个数组:
>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
您可以将重塑看作是首先对数组进行碎片处理(使用给定的索引顺序),然后使用与碎片处理相同的索引顺序将碎片数组中的元素插入到新数组中。
>>> np.reshape(a, (2, 3)) # C-like index ordering
array([[0, 1, 2],
[3, 4, 5]])
>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
array([[0, 1, 2],
[3, 4, 5]])
>>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
array([[0, 4, 3],
[2, 1, 5]])
>>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
array([[0, 4, 3],
[2, 1, 5]])
例子:
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
[5, 6]])