29 Mar Reshape a Numpy array
In Python Numpy, the number of elements in each dimension of an array is called the shape. To reshape the number of dimensions, use the numpy.reshape() method in Python.
Why reshape?
Reshape allows you to edit the number of elements in a dimension. Additionally, with reshape(), you can add or remove dimensions.
Let us see two examples to reshape arrays in NumPy:
- Reshape dimensions from 1D to 2D
- Convert 3D Array to 1D array (Flattening the array)
Reshape dimensions from One-Dimensional to Two-Dimensional
Let us see an example and create a 1D array. We will reshape this 1D array to 2D array using the reshape():
1 2 3 4 5 6 7 8 9 10 11 12 |
import numpy as np # Create a Numpy array n = np.array([5, 10, 15, 20, 25, 30]) print("One-Dimensional Array = ",n) # Reshape the array resarr = n.reshape(2, 3) print("Reshaped array (Two-Dimensional) = \n",resarr) |
Output
1 2 3 4 5 6 |
One-Dimensional Array = [ 5 10 15 20 25 30] Reshaped array (Two-Dimensional) = [[ 5 10 15] [20 25 30]] |
Convert 3D Array to 1D array (Flattening the array)
Let us see an example and create a 3D array. We will reshape this 3D array to 1D array using the reshape():
1 2 3 4 5 6 7 8 9 10 11 |
import numpy as np # Create a 3D array n = np.array([[[5, 10, 15],[20, 25, 30]],[[35, 40, 45],[50, 55, 60]]]) print("3D array = \n ",n) # Reshape the array resarr = n.reshape(-1) print("\nReshaped to 1D array = ",resarr) |
Output
1 2 3 4 5 6 7 8 9 10 |
3D array = [[[ 5 10 15] [20 25 30]] [[35 40 45] [50 55 60]]] Reshaped to 1D array = [ 5 10 15 20 25 30 35 40 45 50 55 60] |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments