Home > Software design >  in order of smallest sum, numpy array
in order of smallest sum, numpy array

Time:11-10

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:

  [[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.

CodePudding user response:

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]])
  • Related