Let’s see how to use numpy reshape method to reshape an array in Numpy Python module.
Example: Reshaping a One-Dimensional Array
Suppose you would like to reshape a one-dimensional array into a two-dimensional one with four rows and six columns.
import numpy as np my_array = np.arange(24) reshaped_array = my_array.reshape(4, 6) print("my array") print(my_array) print("reshaped array") print(reshaped_array)
I used the reshape method on the array. The arguments specify the new shape of the array, not its number of dimensions.
In other words, the first argument will be the number of rows and the second one will be the number of columns.
The reshape
method changes the shape of an array without altering its data. The first argument specifies the number of rows, and the second specifies the number of columns.
Additional Parameters of the reshape
Method
order
: Defines the order of reshaping.C
(default): Reshapes in row-major (C-like) order.F
: Reshapes in column-major (Fortran-like) order.
axes
: Specifies the dimensions of the reshaped array as a list of integers.copy
: IfTrue
, creates a copy of the array. Defaults toFalse
.
Applications of the reshape
Method
The reshape
method is versatile and can be used to:
- Alter the number of dimensions of an array.
- Adjust the size of each dimension.
- Match the shape of another array for operations.
- Prepare data for visualization or storage.