Deleting multiple slices from a numpy array

arrays, numpy, python

Solution

You can use `set()` to identify which positions will be kept and `np.take()` to obtain the corresponding values, doing something like:

ind = np.indices(myarray.shape)[0]
rm = np.hstack([ind[i] for i in mylist])

ans = np.take(myarray, sorted(set(ind)-set(rm)))

Note that `np.hstack()` is used to obtain a single array with all the indices that will be removed. This takes about half the time of @HYRY's solution.

Problem

I have a given numpy array and a list containing a number of slice objects (alternatively containing `(start, end)` tuples). I am looking to remove the slice object positions from the original array and get a second array with the remaining values. Toy example: ``` myarray = np.arange(20) array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) mylist=(slice(2,4),slice(15,19)) ``` Do something and result should be ``` array([0, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) ``` The array can be in a few hundred thousand large, the list of slice objects can contain a few thousand elements and I need to run the operation often, so speed is somewhat important. Numpy delete does not take a list of slices as far I can see? For now I am generating the complement of my slice object list and slicing that, but generating the complement is a somewhat awkward process where I am sorting my slice list then iterating through it, creating the complement slice objects as needed. I am hoping there is a more elegant way I have not figured!

Original source