1

I have an array and I want to get the order of each element.

a=[1.83976,1.57624,1.00528,1.55184]
np.argsort(a)

the above code return

array([2, 3, 1, 0], dtype=int64)

but I want to get the array of the order of each element. e.g.

[0, 1, 3, 2]

means a[0] is largest number (0th)
a[1] is 1th
a[2] is 3rd
a[3] is 2nd
Wenhui
  • 61
  • 5

2 Answers2

1

Ill explain,np.argsort(np.argsort(a)) gives the element in there order like 1.83976 is the highest value in the array so it is assigned the highest value 3. I just subtracted the value from len(a)-1 to get your output.

>>> import numpy as np
>>> a=[1.83976,1.57624,1.00528,1.55184]
>>> np.argsort(a)
array([2, 3, 1, 0])
>>> np.argsort(np.argsort(a))
array([3, 2, 0, 1])
>>> [len(a)-i for i in np.argsort(np.argsort(a))]
[1, 2, 4, 3]
>>> [len(a)-1-i for i in np.argsort(np.argsort(a))]
[0, 1, 3, 2]
>>> np.array([len(a)-1]*len(a))-np.argsort(np.argsort(a))
array([0, 1, 3, 2])
Albin Paul
  • 3,330
  • 2
  • 14
  • 30
0

By default argsort returnes indexes of sorted elements in ascending order. As you need descending order, argsort(-a) will give you right sorted indexes. To get the rank of elements you need to apply argsort again.

a = np.array([1.83976,1.57624,1.00528,1.55184])
indx_sorted = np.argsort(-a)
np.argsort(indx_sorted)
>>> array([0, 1, 3, 2])
  • 1
    Hi! While this may provide an answer, it is generally discouraged on StackOverflow to leave code only answers. Please explain *why* this is a solution as it will help OP and future visitors. Thanks! – d_kennetz Apr 05 '19 at 16:49