5

I need to sort by the first column in descending order an array. To be specific my code is:

>>> x = np.array([[2, 3], [1998,5], [1998,7]])
>>> x = x[np.argsort(x[:,0])]

but the output is

array([[   2,    3],
       [1998,    5],
       [1998,    7]])

but I need it in descending order. Can someone explain me how to do that?

EDIT: @Babyburger suggested this solution :

x = x[np.argsort(x[:,0])][::-1]

that give

array([[1998,    7],
       [1998,    5],
       [   2,    3]])

it could be fine, but i would like that where the value on the first column is the same, the order is not changed. So the output would be

array([[1998,    5],
       [1998,    7],
       [   2,    3]])

is there a simple way to do that?

DomTomCat
  • 8,189
  • 1
  • 49
  • 64
Daniele Sartori
  • 1,674
  • 22
  • 38

1 Answers1

3

in this particular requirement you can use python's sorted which is stable:

a =  np.array([[2, 3], [1998,5], [1998,7]])
res = np.array(sorted(a, key= lambda x: -x[0]))

it does: use the first element of each row for comparison (by lambda accessor) and negate it for decreasing order. By stability, the rows will preserve order if the first element is the same

ouput:

[[1998    5]
 [1998    7]
 [   2    3]]

EDIT: btw if you wanted to sort by the following columns whenever the preceeding ones are identical (all of the same ordering):

a =  np.array([[2, 3], [1998,5], [1998,7]])
res = np.array(sorted(a, key=lambda x:(-x).tolist()))

this converts the rows to lists and then uses sequence comparison. Note in this example it will be sorted decreasingly (hence (-x))

DomTomCat
  • 8,189
  • 1
  • 49
  • 64
  • 1
    I like that you mention that python `sorted` is stable! To clarify to others; this is not the case with `np.argsort` when used with default parameters (`kind="quicksort"`), but is when used with `kind="mergesort"` – Martin Hallén Jun 16 '16 at 11:55