1

Is there a simple way of iterating through a two dimensional array to store maximum value obtained so far while traversing along a particular dimension. For example, i have an array:

[[2 ,  1,  5],
[-1, -1,  4],
[4, 3,  2],
[2 , 3, 4]]

and I would like the following output:

[[2 ,  2,  5],
[-1, -1,  4],
[4, 4,  4],
[2 , 3, 4]]

Thanks!

2 Answers 2

5

Easy; use accumulate:

>>> numpy.maximum.accumulate(a, axis=1)
array([[ 2,  2,  5],
       [-1, -1,  4],
       [ 4,  4,  4],
       [ 2,  3,  4]])
Sign up to request clarification or add additional context in comments.

Comments

0

If computation time is not an issue, you can do something like:

my_new_array = [ [max(my_array[i][:j+1]) for j in range(len(my_array[i]))] for i in range(len(my_array))]

However it is really not computation-time efficient. It would probably be much more efficient to do 2 loops.

1 Comment

Thanks..I will probably go with using loops.

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.