Numpy resize() Function



The Numpy resize() function returns a new array with the specified shape and resizing the input array. The reshape() function is which requires that the total number of elements remain constant where the resize() can change the total number of elements by either truncating or padding the array.

If the new shape is larger than the original then the array is padded with repeated copies of the original data. If it's smaller then the array is truncated.

This function takes the input array and the new shape as arguments and optionally a refcheck parameter to control whether to check for references to the original array.

Syntax

Following is the syntax of Numpy resize() function −

numpy.resize(arr, shape)

Parameters

Below are the parameters of the Numpy resize() function −

  • arr: Input array to be resized.
  • shape: New shape of the resulting array.
  • shape: New shape of the resulting array.

Example 1

Following is the example of Numpy resize() function, which shows how to reshape a 2D array either truncating or repeating elements to fit the new specified dimensions −

import numpy as np

# Create a 2D array
a = np.array([[1, 2, 3], [4, 5, 6]])

print('First array:')
print(a)
print('\n')

print('The shape of the first array:')
print(a.shape)
print('\n')

# Resize the array to shape (3, 2)
b = np.resize(a, (3, 2))

print('Second array:')
print(b)
print('\n')

print('The shape of the second array:')
print(b.shape)
print('\n')

# Resize the array to shape (3, 3)
# Note: This will repeat elements of 'a' to fill the new shape
print('Resize the second array:')
b = np.resize(a, (3, 3))
print(b)

The above program will produce the following output −

First array:
[[1 2 3]
 [4 5 6]]

The shape of first array:
(2, 3)

Second array:
[[1 2]
 [3 4]
 [5 6]]

The shape of second array:
(3, 2)

Resize the second array:
[[1 2 3]
 [4 5 6]
 [1 2 3]]

Example 2

Below is another example of resizing the given array of size 4x3 into 6x2 and 3x4 −

import numpy as np

# Create an initial 4x3 array
array = np.array([[1, 2, 3], [4, 5, 6],[7,8,9],[10,11,12]])

print("Original array:")
print(array)
print("\n")

# Resize the array to shape (6, 2)
resized_array = np.resize(array, (6, 2))

print("Resized array to shape (6, 2):")
print(resized_array)
print("\n")

# Resize the array to shape (3, 4)
resized_array_larger = np.resize(array, (3, 4))

print("Resized array to shape (3, 4) with repeated elements:")
print(resized_array_larger)

The above program will produce the following output −

Original array:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]


Resized array to shape (6, 2):
[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]


Resized array to shape (3, 4) with repeated elements:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
numpy_array_manipulation.htm
Advertisements