Negating a slice in Numpy?

Multi tool use
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:
[:, [2, 4]]
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?
foo
:
np.delete
Right. I stated the question to be a bit more general than I actually need (in case there would have been a generic solution), but I see that arbitrary indexing can choose elements more than once, which makes it hard to interpret what the negation should be. I'll edit the question to reflect what I actually need.
– Edvard Fagerholm
Jul 3 at 9:00
Do you actually want to delete those elements from the original array, or do you want a view on the array without altering the original?
– tobias_k
Jul 3 at 9:02
I don't need the old values, so whatever is the most efficient as I would keep repeating these operations in a loop possibly thousands of times.
– Edvard Fagerholm
Jul 3 at 9:03
If you receive the actual column numbers as input, you can do this manually:
foo[:, sorted(set(range(foo.shape[1])) - set([2, 4]))]
. If your slice is an actual array of values, as Divakar states this problem is ambiguous.– jpp
Jul 3 at 9:06
foo[:, sorted(set(range(foo.shape[1])) - set([2, 4]))]
1 Answer
1
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:
set.difference
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.
numpy.delete
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What if col-0 is same col-2? How would you trace it back without having those indices -2,4?
– Divakar
Jul 3 at 8:53