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 SciPy rankdata function.

For instance, we write

from scipy.stats import rankdata

a = [4, 2, 7, 1]
ranks = rankdata(a)

to call rankdata with list a to return a list with the ranks of the values in a.

The ranks for floats by default.

Conclusion

To rank items in an array using Python NumPy, without sorting array twice, we can use the SciPy rankdata function.

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 *