Use the np.array.argsort() and list.sort() to get the rank of the number

I have a list and I want to get the rank for each member. This is important for many data mining algorithm, for example kNN (k-Nearest-Neighbor), you want to know the rank of a certain record.

For example:

myList = [2, 1, 7, 3, 6]

My expected result:

rank =[1, 0, 4, 2, 3]

Take care, I mean the “rank” not the index of the argument.

Solution 1:

Step 1: Get the sorted index of myList

  • Method 1: use the numpy.array.argsort() to get a list of returned index
    Out: array([1,0,3,4,2])
  • Method 2: use the numpy.array.sort(key=…)
    indices = range[5]
    Out: array([1,0,3,4,2])

Step 2: Turn the index to the rank

  • indices = np.array(myList).argsort()
    [indices.tolist().index(i) for i in range(5)]

Solution 2:

You can do all the things in one strike:

  • ranking = [sorted(list).index(each) for each in list]

Written by connygy. Posted in python

Trackback from your site.

Leave a comment