Reputation: 22529
I am working with np.arrays. I am trying to remove the last n elements, where n can be also 1.
n=5
corr=np.full(10,10)
Usually I use this approach with array slicing:
corr=corr[:-n]
But I was thinking of using np.delete to increase the performance:
np.delete(corr,range(-n,0))
But it doesn't work, is there any better solution compare with array slicing? (method able to deal also with case in which n=0, would be a point of advantage)
Upvotes: 3
Views: 14543
Reputation: 231665
An array is an object with attributes like shape
, dtype
, and a data buffer. A view like A[:-5]
is another array with its own shape
, etc, but with a shared data buffer. It's looking at the same data, but only sees a slice.
A[:-5].copy()
will appear to be the same, but will have its own data buffer, a copy of selected elements from A
.
There's no way of changing the size of the data buffer of A
.
np.delete
returns a new array with its own data buffer. It uses various methods depending on the shape and delete pattern. It all cases it is a copy, and slower than slicing.
Upvotes: 5
Reputation: 18668
Use corr[0:corr.size-n]
. this is the faster way since it is only a view.
np.delete is a copy of the remainding elements.
In [9]: %timeit corr[0:corr.size-5]
1000000 loops, best of 3: 1.45 µs per loop
In [10]: %timeit np.delete(corr,range(corr.size-5,corr.size))
10000 loops, best of 3: 145 µs per loop
Upvotes: 4