Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: argsort in descending order for 2d array?

Tags:

python

arrays

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?

like image 777
Daniele Sartori Avatar asked Oct 19 '22 07:10

Daniele Sartori


1 Answers

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))

like image 69
DomTomCat Avatar answered Oct 21 '22 04:10

DomTomCat