Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negating a slice in Numpy?

Tags:

python

numpy

Let's say that I have an array something like:

foo = np.random.rand(2, 5)

and I've been given a slice like [:, [2, 4]]. What I'd like to do is to efficiently be able to delete the slice out of the array, so basically leaving me with:

foo[:, [0, 1, 3]]

Here foo could be an arbitrary rank tensor with the slice in each dimension being either a : or a list of non-repeating positive indices. Is there an efficient way of implementing this without using np.delete and a complicated (slow) loop?

like image 870
Edvard Fagerholm Avatar asked Jan 17 '26 09:01

Edvard Fagerholm


1 Answers

Given an input list of column indices you wish to remove, you can remove these elements from a list of all indices.

Simpler still, you can utilize set.difference to remove the necessary columns:

foo[:, sorted(set(range(foo.shape[1])) - set([2, 4]))]

To select specific rows or columns, you should not need to use numpy.delete. As you found, this is inefficient with NumPy.

like image 168
jpp Avatar answered Jan 20 '26 01:01

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!