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.
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])