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

Estimated read time 2 min read

To rank items in an array using NumPy in Python without sorting the array twice, you can use the argsort() function in conjunction with the argsort().argsort() method. Here’s an example:

import numpy as np

# Define an array
arr = np.array([7, 3, 1, 2, 6, 4])

# Get the indices that would sort the array
sorted_indices = np.argsort(arr)

# Get the indices that would sort the sorted indices
ranks = np.argsort(sorted_indices)

# Print the ranks
print(ranks)

In this example, we have an array arr with values [7, 3, 1, 2, 6, 4].

To rank the items in the array, we first use np.argsort(arr) to obtain the indices that would sort the array in ascending order. This gives us [2, 3, 1, 5, 4, 0], which represents the sorted indices.

Next, we use np.argsort(sorted_indices) to obtain the indices that would sort the sorted indices. This effectively gives us the ranks of the items in the original array. The resulting array [5, 2, 1, 3, 4, 0] represents the ranks of the items in the original array.

The output will be:

[5 2 1 3 4 0]

In this case, the ranks of the items in the array are [5, 2, 1, 3, 4, 0].

By using argsort() and argsort().argsort() in this manner, we avoid sorting the array twice while obtaining the ranks of the items. This approach is efficient and provides the desired result.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply