1

I have 5 numpy arrays within a single nxm array, with each array containing a set of random values. What I need is to print them according to their decreasing cumulative sums. For instance, my nXm array looks like:

 v = [[1,2,3,4], [2,3,4,5], [11,21,3,4], [4,33,21,1], [2,4,6,5]]

and what I need it to be ordered like is: the one having the highest cumulative sum comes first. I tried printing them according to argmax but it sneaks into all the elements of individual arrays and sorts them in a descending order..

Is there a way?

1 Answer 1

3

Assuming that by cumulative sum you mean total (there's a cumulative sum function which returns something else), then you can do this both using the standard sort:

>>> v = [[1,2,3,4], [2,3,4,5], [11,21,3,4], [4,33,21,1], [2,4,6,5]]
>>> sorted(v, key=sum, reverse=True)
[[4, 33, 21, 1], [11, 21, 3, 4], [2, 4, 6, 5], [2, 3, 4, 5], [1, 2, 3, 4]]

and in numpy using argsort:

>>> a = np.array(v)
>>> a.sum(axis=1)
array([10, 14, 39, 59, 17])
>>> a.sum(axis=1).argsort()
array([0, 1, 4, 2, 3])
>>> a[a.sum(axis=1).argsort()[::-1]]
array([[ 4, 33, 21,  1],
       [11, 21,  3,  4],
       [ 2,  4,  6,  5],
       [ 2,  3,  4,  5],
       [ 1,  2,  3,  4]])

But I may be misunderstanding you.

Sign up to request clarification or add additional context in comments.

Comments

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.