NumPy Tutorial NumPy Statistics NumPy References

NumPy - resize() function



The NumPy resize() function returns a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of a.

Please note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.

Syntax

numpy.resize(a, newshape)

Parameters

a Required. Specify the array to be resized.
newshape Required. Specify the shape of resized array.

Return Value

Returns the new array. It is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated in the order that they are stored in memory.

Example:

In the example below, the resize() function is used to resize a given array.

import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
print("Original Array:")
print(arr)

#resizing array from (2,3) -> (3,2)
print("\nResized Array1:")
print(np.resize(arr, (3,2)))

#resizing array from (2,3) -> (6)
print("\nResized Array2:")
print(np.resize(arr, (6)))

The output of the above code will be:

Original Array:
[[1 2 3]
 [4 5 6]]

Resized Array1:
[[1 2]
 [3 4]
 [5 6]]

Resized Array2:
[1 2 3 4 5 6]

Example:

When the size of the new array is larger than the original array, then the new array is filled with repeated copies of a as shown in the example below.

import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
print("Original Array:")
print(arr)

#resizing array from (2,3) -> (4,3)
print("\nResized Array1:")
print(np.resize(arr, (4,3)))

#resizing array from (2,3) -> (3,3)
print("\nResized Array2:")
print(np.resize(arr, (3,3)))

The output of the above code will be:

Original Array:
[[1 2 3]
 [4 5 6]]

Resized Array1:
[[1 2 3]
 [4 5 6]
 [1 2 3]
 [4 5 6]]

Resized Array2:
[[1 2 3]
 [4 5 6]
 [1 2 3]]

❮ NumPy - Array Manipulation