Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *