Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting multiple slices from a numpy array

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!

like image 727
anordell Avatar asked Jul 08 '14 21:07

anordell


People also ask

How do I delete multiple rows in Numpy?

Using the NumPy function np. delete() , you can delete any row and column from the NumPy array ndarray . Specify the axis (dimension) and position (row number, column number, etc.). It is also possible to select multiple rows and columns using a slice or a list.

How do I delete multiple columns in Numpy?

To delete multiple elements from a numpy array by index positions, pass the numpy array and list of index positions to be deleted to np. delete() i.e. It deleted the elements at index position 1,2 and 3 from the numpy array. It returned a copy of the passed array by deleting multiple element at given indices.

How do I remove an element from a Numpy array?

In case you don't have the indices of the elements you want to remove, you can use the function in1d provided by numpy. The function returns True if the element of a 1-D array is also present in a second array. To delete the elements, you just have to negate the values returned by this function.


1 Answers

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.

like image 63
Saullo G. P. Castro Avatar answered Oct 14 '22 06:10

Saullo G. P. Castro