2

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.

2
  • FYI: You can simplify indices = np.searchsorted(t, edges) to indices = np.ceil(edges).astype(int). That's much more efficient, and you don't need t. Commented Aug 12, 2016 at 15:03
  • @WarrenWeckesser thanks for the suggestion. In the actual use case t is a non-uniformly spaced float array so I think searchsorted is required Commented Aug 12, 2016 at 15:34

1 Answer 1

3

reduceat does the job nicely. I didn't know about that functionality 30 minutes ago.

maxes = np.maximum.reduceat(y, indices)[:-1]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.