48

Say I have some long array and a list of indices. How can I select everything except those indices? I found a solution but it is not elegant:

import numpy as np
x = np.array([0,10,20,30,40,50,60])
exclude = [1, 3, 5]
print x[list(set(range(len(x))) - set(exclude))]
2
  • possible duplicate : stackoverflow.com/questions/7429118/… Commented Nov 28, 2017 at 21:02
  • 2
    @AlperFıratKaya, your link removes just one element, not a list of them. Commented Nov 28, 2017 at 21:24

4 Answers 4

58

This is what numpy.delete does. (It doesn't modify the input array, so you don't have to worry about that.)

In [4]: np.delete(x, exclude)
Out[4]: array([ 0, 20, 40, 60])
Sign up to request clarification or add additional context in comments.

Comments

31

np.delete does various things depending what you give it, but in a case like this it uses a mask like:

In [604]: mask = np.ones(x.shape, bool)
In [605]: mask[exclude] = False
In [606]: mask
Out[606]: array([ True, False,  True, False,  True, False,  True], dtype=bool)
In [607]: x[mask]
Out[607]: array([ 0, 20, 40, 60])

3 Comments

The best solution and one that I assume is the most vectorizable and efficient.
@JoeyCarson, can you please explain why it's better than accepted one?
@ShihabShahriarKhan According to numpy.delete documentation, "Often it is preferable to use a boolean mask ... [It] is equivalent to np.delete(...), but allows further use of mask."
10

np.in1d or np.isin to create boolean index based on exclude could be an alternative:

x[~np.isin(np.arange(len(x)), exclude)]
# array([ 0, 20, 40, 60])

x[~np.in1d(np.arange(len(x)), exclude)]
# array([ 0, 20, 40, 60])

1 Comment

This has the advantage of being usable in assignment. Still, wondering if there isn't something more efficient...
-1

You can also use a list comprehension for the index

>>> x[[z for z in range(x.size) if not z in exclude]]
array([ 0, 20, 40, 60])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.