More efficient way to remove last N values fom np.array

余生长醉 提交于 2021-02-05 09:47:41

问题


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)


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/36480086/more-efficient-way-to-remove-last-n-values-fom-np-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!