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))]
You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
The unique() method is a built-in method in the numpy, that takes an array as input and return a unique array i.e by removing all the duplicate elements. In order to remove duplicates we will pass the given NumPy array to the unique() method and it will return the unique array.
Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.
To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.
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])
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With