How to rank items in an array using NumPy

NumPy is an open-source Python library used for working with arrays. In 2005, Travis Oliphant created NumPy. To import NumPy, we use the function:

import numpy or
import numpy as np

How to rank items in an array using NumPy

To rank items in NumPy, we can use a special method called numpy.argsort(). In the numpy.argsort() method, indices are used to sort arrays in NumPy.

Code

In the example below, the NumPy array is ranked using the argsort() method.

import numpy as np
array = np.array([1,28,14,25,9,3])
temp = array.argsort()
ranks = np.empty_like(temp)
ranks[temp] = np.arange(len(array))
print(array)
print(ranks)

The ranks[temp] = np.arange(len(array)) function is used to rank every element in the array. np.array() is used to create our array.

import numpy as np
array = np.array([2,6,5,3,8])
temp = array.argsort()
ranks = np.empty_like(temp)
ranks[temp] = np.arange(len(array))
print(array)
print(ranks)

Free Resources