Sometimes you want to resize the NumPy array according to your dimension need. There is a function in NumPy to do so and that is numpy.resize(). Just put any array shape inside the method. And then define how many rows or columns you want, and NumPy will convert to that dimension. In this entire tutorial I will show you the implementation of np.resize() using various examples.
Syntax of the numpy.resize() method.
numpy.resize(a, new_shape)
Explanation of Parameters
a: It is your input array of any shape.
new_shpape: New shape of the array you want to return.
The method will return an array with the new shape you have defined.
Steps to Resize Numpy Array
Step 1: Import the required library.
I am using only the NumPy array. So let’s import it,
import numpy as np
Step 2: Follow the following Examples to Resize Numpy Array
Example 1: Resizing a Single Dimension Numpy Array
Let’s create a sample 1D Numpy array and resize it using the resize() method.
array_1d= np.array([1,2,3,4,5,6,7])
Suppose I want to change the dimension of the above array to 3 rows and 2 columns. Then I will pass (3,2) as an argument of the resize() method.
np.resize(array_1d,(3,2))
Output
In the same way, I can create a NumPy array of 3 rows and 5 columns dimensions. Just Execute the given code.
np.resize(array_1d,(3,5))
Output
Example 2: Resizing a Two-Dimension Numpy Array
Now you have understood how to resize as Single Dimensional array. In this section, you will learn to resize a NumPy array of two dimensions. Let’s create a Sample 2 D Array.
array_2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
Output
Now I want to change the 2-D array into the shape of 2 rows and 2 columns. So, I will pass (2,2) as an argument. Run the code given below.
np.resize(array_2d,(2,2))
Output
You can see the created 2D Array is of size 3×3. Using the NumPy resize method you can also increase the dimension. For example, if I want 5 rows and 7 columns then I will pass (5,7) as an argument.
np.resize(array_2d,(5,7))
Output
Conclusion
Numpy resize is a handy function if you want to change the dimension of the existing array. Many readers must be thinking that NumPy reshape() method also do exactly like the resize() method. Yes, they do. But there is a major difference between them. And the difference is that reshape() changes the dimension that is temporary. But in the case of resize()changes are permanent.
I hope this article has cleared your understanding of how to resize the NumPy array. If you want to know more about it then you can contact us.
Source:
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.