NumPy | resize method
Start your free 7-days trial now!
Numpy's resize(~)
method returns a new Numpy array with the desired shape. If the reshaped array contains more values than the original array, then numbers will be repeated.
This is equivalent to Numpy's reshape(~)
method, just without the order
parameter.
Parameters
1. a
| array-like
The input array.
2. new_shape
| int
or tuple
of int
The desired shape of the array.
Return value
A new Numpy array with the desired shape.
The behaviour of a.resize(~) is different
This documentation covers the method np.resize(~)
, which has a different behaviour from a.resize(~)
where a
is the source array.
Firstly, the
a.resize(~)
method performs the resizing in-place, that is, the original array is directly modified without the creation of a new array.Secondly, instead of numbers being repeated in cases where the reshaped array contains more values than the original array, zeros are added.
Examples
Going from 1D to 2D
a = np.array([4,5,6,7])np.resize(a, (2,2))
array([[4, 5], [6, 7]])
Case when values are repeated
Values are repeated when resized array contains more values than the original array:
np.resize([4,5], (2,2))
array([[4, 5], [4, 5]])
Notice how the numbers are simply repeated.
Going from 2D to 1D
Consider the following:
a = np.array([[1,2],[3,4]])a
array([[1, 2], [3, 4]])
To obtain the 1D representation:
np.resize(a, 4)
array([1, 2, 3, 4])