'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?
Solution 1:[1]
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]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
