Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

in order of smallest sum, numpy array

Given this numpy array:

  [[0 4]                     
   [5 0]]

I want to be able to put them in a list in an order of smallest sum, but I want it to work in general, not just for these two data and also for more than 2. i.e. it should also work for this:

  [[0 4]                     
   [5 0]
   [1 2]]

so this would give:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  [[1 2] [0 4] [5 0]]

this is what I got:
order_smallest = []
def smallest_sum(xy):
sums = np.sum(xy, axis=1)

while sums >= 0:
   smallest_sum = np.amin(sums)
   #add smallest_sum to the list order_smallest
   #remove the smallest_sum from the list then?

I thought a loop would work, but I just can’t get it right.

>Solution :

Use argsort on the sum to reindex:

a =  np.array([[0, 4],
               [5, 0],
               [1, 2]])

out = a[np.argsort(a.sum(axis=1))]

output:

array([[1, 2],
       [0, 4],
       [5, 0]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading