numpy.reshape

numpy.reshape(a, newshape, order='C')[源代码]

在不更改数组数据的情况下为数组赋予新形状。

参数
aarray_like

要重新整形的数组。

newshapeint或int的元组

新形状应与原始形状兼容。如果是整数,则结果将是该长度的一维数组。一个形状尺寸可以是-1。在这种情况下,值是从数组的长度和剩余维度推断出来的。

order'C'、'F'、'A',可选

阅读 a 使用此索引顺序,并使用此索引顺序将元素放置到重新整形的数组中。”“C”表示使用类似C的索引顺序读/写元素,最后一个轴索引变化最快,返回到第一个轴索引变化最慢。”f'表示使用类似于Fortran的索引顺序读/写元素,第一个索引更改得最快,最后一个索引更改得最慢。请注意,“c”和“f”选项不考虑底层数组的内存布局,只引用索引顺序。“a”表示以类似于Fortran的索引顺序读取/写入元素,如果 a 是FORTRAN语言 邻接的 在内存中,C-like顺序不同。

返回
reshaped_array恩达雷

如果可能,这将是一个新的视图对象;否则,它将是一个副本。注:不保证 内存布局 (c-或fortran-连续)返回的数组。

参见

ndarray.reshape

等效方法。

笔记

在不复制数据的情况下,不可能总是更改数组的形状。如果希望在复制数据时引发错误,应将新形状指定给数组的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 in-place modification. Use
`.reshape()` to make a copy with the desired shape.

这个 order 关键字给出了索引的顺序 取来 值来自 a 然后 放置 输出数组中的值。例如,假设您有一个数组:

>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
       [2, 3],
       [4, 5]])

您可以将重塑视为首先对数组进行Raveling(使用给定的索引顺序),然后使用与Raveling相同的索引顺序将Raveled数组中的元素插入新数组。

>>> 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]])