0

I have NumPy array and need to sort it by two columns (first by column 0 and then sort equal values by column 1), both in descending order. When I try to sort sequentially by column 1 and column 0, the rows equal in the second sorting turn to be sorted in ascending order in the first sorting.

My array:

arr = np.array([
    [150, 8],
    [105, 20],
    [90, 100],
    [101, 12],
    [110, 80],
    [105, 100],
])

When I sort twice (by column 1 and column 0):

arr = arr[arr[:,1].argsort(kind='stable')[::-1]]
arr = arr[arr[:,0].argsort(kind='stable')[::-1]]

I have this result (where rows 2 and 3 are swapped):

array([[150,   8],
       [110,  80],
       [105,  20],
       [105, 100],
       [101,  12],
       [ 90, 100]])

As far as I understand, it happens because stable mode preserves the original order for equal values, but when we flip the indices to make the order descend, the original order changes too.

The results I'd like to have:

array([[150,   8],
       [110,  80],
       [105, 100],
       [105,  20],
       [101,  12],
       [ 90, 100]])
Boris Silantev
  • 753
  • 3
  • 13

1 Answers1

3

Use numpy.lexsort to sort on multiple columns at the same time.

arr = np.array([
    [150, 8],
    [105, 20],
    [90, 100],
    [101, 12],
    [110, 80],
    [105, 100],
])

order = np.lexsort([arr[:, 1], arr[:, 0]])[::-1]
arr[order]

yields:

array([[150,   8],
       [110,  80],
       [105, 100],
       [105,  20],
       [101,  12],
       [ 90, 100]])
myrtlecat
  • 2,156
  • 12
  • 16