NumPy Tutorial NumPy Statistics NumPy References

NumPy - ndarray.resize() function



The NumPy ndarray.resize() function changes shape and size of array in-place. If the new array is larger than the original array, then the new array is filled with zeros.

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

Syntax

numpy.ndarray.resize(newshape)

Parameters

newshape Required. Specify the shape of resized array.

Return Value

None.

Example:

In the example below, the ndarray.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)
arr.resize((3,2))
print("\nResized Array:")
print(arr)

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

The output of the above code will be:

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

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

Resized Array:
[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 zeros 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)
arr.resize((4,3))
print("\nResized Array:")
print(arr)

The output of the above code will be:

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

Resized Array:
[[1 2 3]
 [4 5 6]
 [0 0 0]
 [0 0 0]]

❮ NumPy - Array Manipulation