numpy.reshape(a,newshape,order='C')[source]¶Gives a new shape to an array without changing its data.
| Parameters: | a : array_like
newshape : int or tuple of ints
order : {‘C’, ‘F’, ‘A’}, optional
|
|---|---|
| Returns: | reshaped_array : ndarray
|
See also
ndarray.reshapeNotes
It is not always possible to change the shape of an array withoutcopying the data. If you want an error to be raise if the data is copied,you should assign the new shape to the shape attribute of the array:
>>>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
Theorder keyword gives the index ordering both forfetching the valuesfroma, and thenplacing the values into the output array.For example, let’s say you have an array:
>>>a=np.arange(6).reshape((3,2))>>>aarray([[0, 1], [2, 3], [4, 5]])
You can think of reshaping as first raveling the array (using the givenindex order), then inserting the elements from the raveled array into thenew array using the same kind of index ordering as was used for theraveling.
>>>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]])
Examples
>>>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]])