Reputation: 1272
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 !
Upvotes: 3
Views: 252
Reputation: 88236
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)
Upvotes: 6