numpy.resize() – The NumPy resize Python Function

Introduction to NumPy resize

We can resize the size of an array using Numpy’s numpy.resize() function. Arrays can be of any form, but we just need the size to resize them, such as (2, 2), (2, 3), and so on. If values at a certain location are lacking, NumPy appends zeros during resizing.

Syntax:

numpy.resize(a, new_shape)

Parameters:

  • a: [array_like] input array
  • new_shape : [tuple of ints, or n ints] Shape of resized array
  • refcheck : [bool, optional] This parameter is used to check the reference counter. By default it is True.

Return: reshaped [ndarray]

Code Examples of NumPy resize

Example 01: In this example, we can see that with the help of the .resize() method, we have changed the shape of an array from 1×6 to 3×3.

# welcome to softhunt.net
# importing the python module numpy
import numpy as np

# Making a random array
softhunt = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15])

# Reshape the array permanently
softhunt.resize(3, 3)

print(softhunt)

Output:

[[ 0  1  3]
 [ 5  7  9]
 [11 13 15]]

Example 02: We can see in this example that we’re attempting to enlarge the array of that shape, which is the type of out of bound values. Numpy, on the other hand, solves this problem by appending zeros to the array when no values are available.

# welcome to softhunt.net
# importing the python module numpy
import numpy as np

# Making a random array
softhunt = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15])

# Reshape the array permanently
softhunt.resize(4, 4)

print(softhunt)

Output:

[[ 0  1  3  5]
 [ 7  9 11 13]
 [15  0  0  0]
 [ 0  0  0  0]]

Note: These programs will not run in online IDEs. Please test them on your systems to see how they operate.

FAQs

What is the Difference Between np.reshape and np.resize

Most of you are probably wondering what the difference is between np.reshape() and np.resize(). When we talk about reshape, we’re talking about a temporary modification to an array’s form, but when we talk about resize, we’re talking about permanent alterations.

Can you declare an array without array size?

No. It is not possible to declare an array without specifying the size. If at all you want to do that, then you can use ArrayList which is dynamic in nature.

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. numpy.append() – The NumPy append Python Function

Leave a Comment