Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an array in Python3 / Numpy and return indices

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...

like image 723
Ekaterina Mishina Avatar asked Mar 27 '12 14:03

Ekaterina Mishina


People also ask

How to filter the element in the NumPy array using Python?

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?

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.

What is the default value for the axis in NumPy?

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.

How to use NumPy in1d() function in Python?

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.


1 Answers

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.

like image 155
Hooked Avatar answered Nov 09 '22 23:11

Hooked