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)
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources