Filter an array in Python3 / Numpy and return indices
You can get the indices of the elements in the one-dimensional array a
that are greater than min_value
and les than max_value
with
indices = ((min_value < a) & (a < max_value)).nonzero()[0]
Usually you don't need those indices, though, but you can work more efficiently with the mask
mask = (min_value < a) & (a < max_value)
This mask is an Boolean array with the same shape as a
.
Edit: If you have an array b
of the same shape as a
, you can extract the elements of b
corresponding to the True
entries in mask
with
b[mask]
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.
Not directly related to your question, but filter()
is part of a set of three functions, map()
, filter()
, and reduce()
, which allow functional-style list processing in Python.
map(mapping_function, input_list)
takes in a function of one argument and a list, applies the function to each element of the list in turn, and returns an output list as the result. It's more or less equivalent to the list comprehension[mapping_function(item) for item in input_list]
.filter(filter_function, input_list)
returns a list of elements frominput_list
for which thefilter_function
returnedTrue
. The list comprehension equivalent is[item for item in items if filter_function(item)]
.reduce(combining_function, input_list)
repeatedly combines adjacent pairs of elements in the input list until only one value is left. For example the sum of a list of numbers could be expressed asreduce(operator.add, numbers)
.
The functionality of map()
and filter()
is provided by list comprehensions in Python (which is why the map
and filter
functions aren't used very often.)
reduce()
is one of those things which doesn't suggest itself as an intuitive answer to... anything. It's almost always clearer to write a loop, which explains why you don't see it often.