Reputation: 2651
How can I get rid of the python for loop? t is not uniformly spaced in general (just in the simple example). Solutions using pandas are also fine.
import numpy as np
n = 100
t = np.arange(n)
y = np.arange(n)
edges = np.array([2., 5.5, 19, 30, 50, 72, 98])
indices = np.searchsorted(t, edges)
maxes = np.zeros(len(edges)-1)
for i in range(len(edges)-1):
maxes[i] = np.max(y[indices[i]:indices[i+1]])
print(maxes)
Update: I think reduceat might do it but I don't understand the syntax.
Upvotes: 2
Views: 217
Reputation: 2651
reduceat does the job nicely. I didn't know about that functionality 30 minutes ago.
maxes = np.maximum.reduceat(y, indices)[:-1]
Upvotes: 3