Find indices of the elements smaller than x in a numpy array

Solution 1:

You can use numpy.flatnonzero on the boolean mask and Return indices that are non-zero in the flattened version of a:

np.flatnonzero(arr < 6)
# array([1, 2, 3, 5, 6])

Another option on 1d array is numpy.where:

np.where(arr < 6)[0]
# array([1, 2, 3, 5, 6])

Solution 2:

The simplest way one can do this is by

arr[arr<6]

Solution 3:

I'd suggest a cleaner and self-explainable way to do so: First, find the indices where the condition is valid:

>> indices = arr < 6
>> indices
>> [False, True, True, True, False, True, False]

Then, use the indices for indexing:

>> arr[indices]
>> [1, 2, 5, 2, 3]

or for finding the right position in the original array:

>> np.where(indices)[0]
>> [1, 2, 3, 5, 6]