numpy.ndarray.resize#
method
- ndarray.resize(new_shape, /, *, refcheck=True) a.resize(*new_shape, refcheck=True)#
- ndarray.resize(*new_shape, refcheck=True) None
Change shape and size of array in-place.
- Parameters:
- new_shapetuple of ints, or n ints
Shape of resized array.
- refcheckbool, optional
If False, reference count will not be checked. Default is True. See Notes below for more explanation.
- Returns:
- None
- Raises:
- ValueError
If a does not own its own data or references or views to may exist.
See also
resizeReturn a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
Reallocating arrays in-place can often lead to memory fragmentation and should be avoided. If the goal is to reclaim over-allocated memory, alternatives are to create a view or a copy of just the desired data, or using two passes to build the array: one to cheaply determine the shape and another to allocate and fill. Benchmark your use case to determine what is optimum. You may be surprised to find
resizeactually slows down or bloats your application.The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory.
On Python 3.13 and older, the check allows objects with exactly one reference to be reallocated in-place. On Python 3.14 and newer, the array must be uniquely referenced. See [1] for more details.
If you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.
References
[1]Python 3.14 What’s New, https://docs.python.org/3/whatsnew/3.14.html#whatsnew314-refcount
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:
>>> import numpy as np
>>> a = np.array([[0, 1], [2, 3]], order='C') >>> a.resize((2, 1)) >>> a array([[0], [1]])
>>> a = np.array([[0, 1], [2, 3]], order='F') >>> a.resize((2, 1)) >>> a array([[0], [2]])
Enlarging an array: as above, but missing entries are filled with zeros:
>>> b = np.array([[0, 1], [2, 3]]) >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple >>> b array([[0, 1, 2], [3, 0, 0]])
Referencing an array prevents resizing…
>>> c = a >>> a.resize((1, 1)) Traceback (most recent call last): ... ValueError: cannot resize an array that references or is referenced ...
Unless refcheck is False:
>>> a.resize((1, 1), refcheck=False) >>> a array([[0]]) >>> c array([[0]])