Skip to content
Advertisement

Find the first and last element of a NumPy array larger than a threshold

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?

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)

test = np.random.uniform(0, 1, 100)
above_threshold = test > 0.95
plt.plot(above_threshold)

indices = np.nonzero(above_threshold)
imin = np.min(indices)
imax = np.max(indices)

print(imin, imax)

Advertisement

Answer

You could just access the first/last elements

s = np.flatnonzero(test > 0.95)
imin, imax = s[0], s[-1]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement