Edvard Fagerholm
Edvard Fagerholm

Reputation: 862

Negating a slice in 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?

Upvotes: 3

Views: 302

Answers (1)

jpp
jpp

Reputation: 164773

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.

Upvotes: 2

Related Questions