NumPy ndarray.resize()

The numpy.ndarray.resize() method changes the shape of an existing NumPy array in-place. If the new shape is larger, it fills the new elements with zeroes.

Syntax

</>
Copy
ndarray.resize(new_shape, refcheck=True)

Parameters

ParameterTypeDescription
new_shapen ints or tuple of intsThe desired shape of the array. If the total elements mismatch, data is either truncated or repeated.
refcheckbool, optionalIf False, disables reference checking, allowing resizing even if the array is referenced elsewhere.

Return Value

This method modifies the array in place and does not return a new array. If the new shape is larger, it fills new elements with 0.


Examples

1. Resizing a 1D Array to a Larger Size

In this example, we resize a 1D NumPy array to a larger shape, demonstrating how data repetition occurs.

</>
Copy
import numpy as np  

# Create a 1D array with 3 elements
arr = np.array([1, 2, 3])  

# Resize to 6 elements (larger size)
arr.resize(6)  

print(arr)  # New elements are filled with 0

Output:

[1 2 3 0 0 0]

The extra elements are filled with 0.

2. Resizing a 2D Array to a Smaller Shape

Here, we shrink a 2D array to a smaller shape, where excess elements are discarded.

</>
Copy
import numpy as np  

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

# Resize to a 2x2 array (smaller size)
arr.resize((2, 2))  

print(arr)  # The extra elements are removed

Output:

[[1 2]
 [3 4]]

The remaining elements are taken in row-major order (left to right, top to bottom).

3. Resizing While Keeping References with refcheck=False

We disable reference checking to allow resizing even when the array is referenced elsewhere.

</>
Copy
import numpy as np  

# Create a 1D array
arr = np.array([10, 20, 30, 40])  

# Create a reference to the array
arr_ref = arr  

# Resize with refcheck=False to avoid reference errors
arr.resize(6, refcheck=False)  

print(arr)  # The array is resized successfully

Output:

[10 20 30 40  0  0]

Even though arr is referenced elsewhere, refcheck=False allows resizing.

4. Resizing a 2D Array to a Different Shape

We transform a 2D array into a different shape, keeping elements in row-major order.

</>
Copy
import numpy as np  

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

# Resize to a 3x2 array
arr.resize((3, 2))  

print(arr)  # The shape changes while preserving row-major order

Output:

[[1 2]
 [3 4]
 [5 6]]

The array is rearranged to fit the new dimensions while preserving order.