How to rank items in an array using Python NumPy, without sorting array twice?

Sometimes, we want to rank items in an array using Python NumPy, without sorting array twice.

In this article, we’ll look at how to rank items in an array using Python NumPy, without sorting array twice.

How to rank items in an array using Python NumPy, without sorting array twice?

To rank items in an array using Python NumPy, without sorting array twice, we can use the argsort method.

For instance, we write:

import numpy

array = numpy.array([4, 2, 7, 1])
order = array.argsort()
ranks = order.argsort()
print(order)
print(ranks)

We create a NumPy array with numpy.array with a list of numbers.

Then we call array.argsort to get the order of each item in the array.

And we call order.argsort to get the ranking of each value in the array.

Therefore, we see:

[3 1 0 2]
[2 1 3 0]

printed.

Conclusion

To rank items in an array using Python NumPy, without sorting array twice, we can use the argsort method.