How to select all elements in a NumPy array except for a sequence of indices
Question:
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))]
Answers:
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])
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])
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])
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])
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))]
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])
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])
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])
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])