The reshape()
method changes the shape of a NumPy array without changing its data.
Example
import numpy as np
# create an array
originalArray = np.array([0, 1, 2, 3, 4, 5, 6, 7])
# reshape the array
reshapedArray = np.reshape(originalArray, (2, 4))
print(reshapedArray)
'''
Output
[[0 1 2 3]
[4 5 6 7]]
'''
reshape() Syntax
The syntax of reshape()
is:
numpy.reshape(array, shape, order)
reshape() Arguments
The reshape()
method takes three arguments:
array
- an original array that is to be reshapedshape
- desired new shape of the array (can be integer or tuple of integers)order
(optional) - specifies the order in which the array elements are reshaped.
reshape() Return Value
The reshape()
method returns the reshaped array.
Note: The reshape()
method throws an error if the shape doesn't match the number of elements.
Example 1: Reshape 1D Array to 3D Array
import numpy as np
# create an array
originalArray = np.array([0, 1, 2, 3, 4, 5, 6, 7])
# reshape the array to 3D
reshapedArray = np.reshape(originalArray, (2, 2, 2))
print(reshapedArray)
Output
[[[0 1] [2 3]] [[4 5] [6 7]]]
Using Optional Order Argument in reshape()
The order
argument specifies the order in which the array elements are reshaped.
The order can be:
'C'
- elements are stored row-wise'F'
- elements are stored column-wise'A'
- elements are stored based on the original array's memory layout.
Example 2: Reshape Array Row-Wise
import numpy as np
originalArray = np.array([0, 1, 2, 3, 4, 5, 6, 7])
# reshape the array to 2D
# the last argument 'C' reshapes the array row-wise
reshapedArray = np.reshape(originalArray, (2, 4), 'C')
print(reshapedArray)
Output
[[0 1 2 3] [4 5 6 7]]
Example 3: Reshape Array Column-Wise
import numpy as np
originalArray = np.array([0, 1, 2, 3, 4, 5, 6, 7])
# reshape the array to 2D
# the last argument 'F' reshapes the array column-wise
reshapedArray = np.reshape(originalArray, (2, 4), 'F')
print(reshapedArray)
Output
[[0 2 4 6] [1 3 5 7]]
Example 4: Flatten a Multidimensional Array to 1D Array
In our previous examples, we used tuples as the shape
argument (second argument), which determines the shape of the new array.
However, if we use -1 as a shape
argument, the reshape()
method reshapes the original array into a one-dimensional array.
import numpy as np
originalArray = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
# flatten the array
# to flatten the array, -1 is used as the second argument
reshapedArray = np.reshape(originalArray, -1)
print(reshapedArray)
Output
[0 1 2 3 4 5 6 7]