numpy.reshape
numpy.reshape(a, newshape, order='C') [source]
在不更改数据的情况下为数组赋予新的shape。
参数 : | a :array_like 要重塑的数组。 newshape :int 或 int类型的tuple 新形状应与原始形状兼容。 如果是整数,则结果将是该长度的一维数组。 一个形状尺寸可以为 或der : 使用此索引顺序读取a的元素,然后使用此索引顺序将元素放入重新排列的数组中。 “C”表示使用类似C的索引顺序读取/写入元素,最后一个轴索引更改最快, 回到第一个轴索引更改最慢。 “ F”表示使用类似于Fortran的索引顺序读取/写入元素, 第一个索引更改最快,最后一个索引更改最慢。 请注意,“C”和“F”选项不考虑基础数组的内存布局, 仅参考索引的顺序。 “a”表示如果a在内存中是连续的, 则以类似于Fortran的索引顺序读取/写入元素,否则为类似于C的顺序。 |
返回值 : | reshaped_array :ndarray 如果可能的话,这将是一个新的视图对象; 否则,它将是副本。 注意,不能保证返回数组的内存布局(C或Fortran连续)。 |
Notes
在不复制数据的情况下,并非总是可以更改数组的形状。 如果希望在复制数据时引发错误,则应将新形状分配给数组的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))>>> aarray([[0, 1], [2, 3], [4, 5]])
您可以将重塑看作是首先对数组进行碎片处理(使用给定的索引顺序),然后使用与碎片处理相同的索引顺序将碎片数组中的元素插入到新数组中。
>>> np.reshape(a, (2, 3)) # C-like index orderingarray([[0, 1, 2], [3, 4, 5]])>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshapearray([[0, 1, 2], [3, 4, 5]])>>> np.reshape(a, (2, 3), order='F') # Fortran-like index orderingarray([[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 2array([[1, 2], [3, 4], [5, 6]])