I need to find the first and the last element of a numpy.ndarray
which are above a specified threshold. I found the following solution, which works, but it looks a bit convoluted. Is there a simpler/more Pythonic way?
JavaScript
x
14
14
1
import numpy as np
2
import matplotlib.pyplot as plt
3
np.random.seed(1)
4
5
test = np.random.uniform(0, 1, 100)
6
above_threshold = test > 0.95
7
plt.plot(above_threshold)
8
9
indices = np.nonzero(above_threshold)
10
imin = np.min(indices)
11
imax = np.max(indices)
12
13
print(imin, imax)
14
Advertisement
Answer
You could just access the first/last elements
JavaScript
1
3
1
s = np.flatnonzero(test > 0.95)
2
imin, imax = s[0], s[-1]
3