原文:https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
校对:(虚位以待)
numpy.
reshape
(a, newshape, order='C')[source]为数组提供新形状,而不更改其数据。
参数: | a:array_like
newshape:int或tuple的整数
order:{'C','F','A'},可选
|
---|---|
返回: | reshaped_array:ndarray
|
也可以看看
ndarray.reshape
笔记
在不复制数据的情况下,不能始终更改数组的形状。如果你想要一个错误,如果数据被复制,你应该分配新的形状到数组的shape属性:
>>> a = np.zeros((10, 2))
# A transpose make 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)
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]])