Issue
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.
If value is greater than the previous replace with previous in Pandas
Most efficient way to forward-fill NaN values in numpy array
Solution
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])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.