NumPy | reshape method
reshape(~) method returns a new NumPy array with the desired shape. If the reshaped array contains more values than the original array, then numbers will be repeated.
The input array.
The desired shape. If
-1 is passed, then the shape is inferred. Check our examples below for clarification.
A new NumPy array with the desired shape.
Converting from 1D to 2D
Consider the following 1D array:
a = np.array([1,2,3,4,5,6])aarray([1, 2, 3, 4, 5, 6])
To change this to a 2D array with 2 rows and 3 columns:
np.reshape(a, (2,3))array([[1, 2, 3],[4, 5, 6]])
To convert a 1D array to a 2D array with one element:
array([[1, 2, 3, 4, 5, 6]])
Converting from 2D to 1D
Suppose we have the following 2D array:
a = np.array([[1,2],[3,4]])aarray([[1, 2],[3, 4]])
To obtain the 1D representation:
np.reshape(a, 4)array([1, 2, 3, 4])
Here, we could simply use the
ravel(~) method to flatten the array:
Inferring the shape
shape tells NumPy to infer the suitable shape. For instance:
We could have manually specified
[4,-1] as the shape, but the number of resulting rows can be inferred from:
the number of values there are in the array
the number of columns (
1in this case).