1

I have an unsorted array of integers, and I want to fill all decreasing numbers with the previous larger value.

Example:

>>> np.array([10, -1, 2, 5, 19, 5, 5, 4, 10, 2]) [10 10 10 10 19 19 19 19 19 19] >>> np.array([0, 3, 5, 4, 3, 7, 2] [0 3 5 5 5 7 7] 

I've come up with this solution, but it has to be a more elegant way of doing it.

def func(a): a = a.copy() for i in range(1, a.shape[0]): if a[i] < a[i-1]: a[i] = a[i-1] return a 

Any suggestions?

I have looked at two similar questions, but I am unable to modify the examples to make them work the way I intend.

  1. If value is greater than the previous replace with previous in Pandas

  2. Most efficient way to forward-fill NaN values in numpy array

0

1 Answer 1

0

You can use numpy.maximum.accumulate:

np.maximum.accumulate([10, -1, 2, 5, 19, 5, 5, 4, 10, 2]) # array([10, 10, 10, 10, 19, 19, 19, 19, 19, 19]) np.maximum.accumulate([0, 3, 5, 4, 3, 7, 2]) # array([0, 3, 5, 5, 5, 7, 7]) 
Sign up to request clarification or add additional context in comments.

1 Comment

Of course it had to be this simple... thanks, man!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.