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, 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 the numpy.resize() method.
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 them,
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.
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.
In the same way, I can create a NumPy array of 3 rows and 5 columns dimensions. Just Execute the given code.
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]])
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.
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, I want 5 rows and 7 columns then I will pass (5,7) as an argument.
Numpy resize is a very useful 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 among 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.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.