user184868
user184868

Reputation: 183

Select indexes of intervals in Numpy

Assuming you have some 1d- numpy array like arr = np.array([0,0,0.2,0.6,1,1,0.7,0.3,0,0])

Here if would be fn(arr, arr > 0.5) => [(3,6)] <- indexes of inverval where the values are biggen then given value. Also there can be multiple intervals per each row, so the output [(3,6),[300,302]...] is also possible.

Is it possible to do one-line, or any short written and optimal Numpy operation to get indexes of interval with specific condition?

Upvotes: 0

Views: 470

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

Try:

arr = np.array([0, 0, 0.2, 0.6, 1, 1, 0.7, 0.3, 0, 0])

ranges = np.where(np.diff(arr > 0.5, prepend=0, append=0))[0].reshape(-1, 2)
ranges[:, 1] -= 1

print(ranges)

Prints:

[[3 6]]

For:

arr = np.array([0.6, 0.7, 0, 0, 0.8, 0.9])

Prints:

[[0 1]
 [4 5]]

Upvotes: 1

Related Questions