I’m using numpy.delete to remove elements from an array that is inside a while loop.
This while loop is valid only if the array is not empty. This code works fine but slows down
considerably when the array has over 1e6 elements. Here is an example:
while(array.shape[0] > 0):
ix = where((array >= x) & (array <= y))[0]
array = delete(array,ix,None)
I’ve tried to make this code efficient but I cannot find a good way to speed up the while loop. The bottleneck here is, I think, the delete which must involve a copy of some kind. I’ve tried using masked array in order to avoid copying but I’m not that good at python and masked array are not that easy to search. Is there a good and fast way to use delete or replace it so that 7e6 elements can be handled by the loop above without taking 24 hours?
Thanks
So you can substantially improve the performance of your code by:
eliminating the loop; and
avoiding the delete operations (which cause a copy of the original
array)
NumPy 1.7 introduced a new mask that is far easier to use than the original; it’s performance is also much better because it’s part of the NumPy core array object. I think this might be useful to you because by using it you can avoid the expensive delete operation.
In other words, instead of deleting the array elements you don’t want, just mask them. This has been suggested in other Answers, but i am suggesting to use the new mask
to use NA, just import NA
then for a given array, set the maskna flag to True
Alternatively, most array constructors (as of 1.7) have the parameter maskna, which you can set to True
Often this is not what you want–i.e., you still want the sum of that column with the NA treated as if it were 0:
To get that behavior, pass in True for the skipma parameter (most NumPy array constructors have this parameter in NumPy 1.7):
In sum, to speed up your code, eliminate the loop and use the new mask:
The NA placeholders–in this context–behave like 0s, which i believe is what you want: