Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize NumPy array to smaller size without copy

When I shrink a numpy array using the resize method (i.e. the array gets smaller due to the resize), is it guaranteed that no copy is made?

Example:

a = np.arange(10)            # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a.resize(5, refcheck=False)  # array([0, 1, 2, 3, 4])

From my understanding this should always be possible without making a copy. My question: Does the implementation indeed guarantee that this is always the case? Unfortunately the documentation of resize says nothing about it.

like image 767
luator Avatar asked Sep 04 '15 12:09

luator


People also ask

How do I reduce the size of a NumPy array?

You can use numpy. squeeze() to remove all dimensions of size 1 from the NumPy array ndarray . squeeze() is also provided as a method of ndarray .

How do I change the size of an array in NumPy?

The shape of the array can also be changed using the resize() method. If the specified dimension is larger than the actual array, The extra spaces in the new array will be filled with repeated copies of the original array.

How do I scale a NumPy array?

Use numpy. abs(x) to convert the elements of array x to their absolute values. Use numpy. amax(a) with this result to calculate the maximum value in a . Divide a number x by the maximum value and multiply by the original array to scale the elements of the original array to be between -x and x .

Which function is used to resize a NumPy array in Python?

Resize() resize() function is used to create a new array of different sizes and dimensions. resize() can create an array of larger size than the original array.


1 Answers

A numpy array is a fixed size array in the background, any type of resizing will always copy the array.

Having that said, you could create a slice of the array effectively only using a subset of the array without having to resize/copy.

>>> import numpy
>>> a = numpy.arange(10)
>>> b = a[:5]
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b
array([0, 1, 2, 3, 4])
>>>
>>> a += 10
>>> a
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> b
array([10, 11, 12, 13, 14])
>>>
>>> b += 10
>>> a
array([20, 21, 22, 23, 24, 15, 16, 17, 18, 19])
>>> b
array([20, 21, 22, 23, 24])
like image 97
Wolph Avatar answered Sep 30 '22 21:09

Wolph