Is there any built-in function in Python3/Numpy which filters an array and returns indices of the elements which are left? Something similar to numpy.argsort for sorting. The filter I have is setting both min and max thresholds - all values below/above min/max have to be filtered out.
I've seen Python's function filter, but I don't see a way to extract indices using it.
EDITED: Lots of useful information in the answers, thank you!
As @SvenMarnach pointed out, mask is enough:
mask = (min_value < a) & (a < max_value)
Now I have to apply this mask to other arrays of the same shape as a
, but not sure what is the best way to do it...
In this section, we will discuss how to filter the element in the NumPy array by using Python. In Python, the filter is used to get some values from the given array and then return a new array. To perform this particular task we are going to use the from.iter () method.
How to get the indices of the sorted array using NumPy in Python? 1 Python3. import numpy as np. array = np.array ( [10, 52, 62, 16, 16, 54, 453]) print(array) indices = np.argsort (array) print(indices) Output: [ 10 ... 2 Python3. 3 Python3.
The default value for the axis is None, If none the flatten array is used. In this example, we filter the numpy array by a list of indexes by using the np. take () function and passed the axis=0 to filtering the numpy array row-wise.
In Python, the np.in1d () function takes two numpy arrays and it will check the condition whether the first array contains the second array elements or not. In Python, the np.1d () function always returns a boolean array. Now let’s have a look at the Syntax and understand the working of np.in1d () function.
The command numpy.where
will return the indices of an array after you've applied a mask over them. For example:
import numpy as np
A = np.array([1,2,3,6,2])
np.where(A>2)
gives:
(array([2, 3]),)
A more complicated example:
A = np.arange(27).reshape(3,3,3)
np.where( (A>10) & (A<15) )
gives:
(array([1, 1, 1, 1]), array([0, 1, 1, 1]), array([2, 0, 1, 2]))
I'll agree with @SvenMarnach, usually you don't need the indices.
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