3

I think this is a relatively easy question since I know there is a simple answer in numpy, but I can't find it anymore.

I have a numpy array, say [1, 2, 10, 5, 6, 12, 9, 9, 8]

I want to go through it from beginning to end and to keep only the maximum value seen so far, for example the answer would be [1, 2, 10, 10, 10, 12, 12, 12, 12]

It is very easy to solve with a single loop but some times ago I learned about a numpy function that does the job quickly and that is also compact. I am looking for this method.

Thanks !

1 Answer 1

6

You can use numpy.ufunc.accumulate, to accumulate the result of applying a function, maximum in this case, over all elements:

a = np.array([1, 2, 10, 5, 6, 12, 9, 9, 8])

np.maximum.accumulate(a)
# array([ 1,  2, 10, 10, 10, 12, 12, 12, 12], dtype=int32)
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.