In this article, you will learn how to use the Numpy reshape() function in Python.
Numpy reshape() Function
The numpy.reshape() function in Python is used to change the shape of an array without changing its data. It returns a new array with the same data but with a new shape.
The syntax for the numpy.reshape() function is as follows:
numpy.reshape(arr, newshape, order='C')
arr: The array that you want to reshape
newshape: The new shape that you want to give to the array
order: Specifies the order in which the elements should be read from the original array. The two options are ‘C’ (row-major, or C-style, order) and ‘F’ (column-major, or Fortran-style, order). The default is ‘C’.
The newshape parameter can be a tuple or an integer. If it is an integer, it will be treated as a one-element tuple.
Here’s an example that demonstrates how to use the numpy.reshape() function:
import numpy as np # create a 1D array a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # reshape the array into a 2D array with 5 rows and 2 columns b = np.reshape(a, (5, 2)) print(b) # Output: [[ 1 2] [ 3 4] [ 5 6] [ 7 8] [ 9 10]]
In the above example, we first created a 1D array a with 10 elements. Then, we used the numpy.reshape() function to reshape the array a into a 2D array with 5 rows and 2 columns. Finally, we printed the reshaped array b.
The numpy.reshape() function can also be used to flatten a multi-dimensional array into a 1D array. To do this, you can pass -1 as the newshape parameter. For example:
import numpy as np # create a 2D array a = np.array([[1, 2], [3, 4], [5, 6]]) # flatten the array into a 1D array b = np.reshape(a, -1) print(b) # Output: [1 2 3 4 5 6]
In the above example, we used the numpy.reshape() function to flatten a 2D array a into a 1D array b. We passed -1 as the newshape parameter to tell NumPy to figure out the size of the new shape automatically.
Note that the total number of elements in the original array should be equal to the total number of elements in the reshaped array. Otherwise, you will get a ValueError exception.