Make a numpy array monotonic without a Python loop

前端 未结 1 1323
滥情空心
滥情空心 2020-12-06 05:00

I have a 1D array of values which is supposed to be monotonic (let\'s say decreasing), but there are random regions where the value increases with index.

I need an a

相关标签:
1条回答
  • 2020-12-06 05:30

    You can use np.minimum.accumulate to collect the minimum values as you move through the array:

    >>> np.minimum.accumulate(a)
    array([ 10. ,   9.5,   8. ,   7.2,   7.2,   7.2,   7. ,   5. ,   3. ,
             2.5,   2.5,   2. ])
    

    At each element in the array, this function returns the minimum value seen so far.

    If you wanted an array to be monotonic increasing, you could use np.maximum.accumulate.

    Many other universal functions in NumPy have an accumulate method to simulate looping through an array, applying the function to each element and collecting the returned values into an array of the same size.

    0 讨论(0)
提交回复
热议问题