How To Use Np.argsort In Descending Order In Python

While I was working on a data analysis project where I needed to rank NBA player statistics in descending order. The challenge was to maintain the original data while creating an index of the highest-to-lowest values.

In Python, NumPy’s argsort() function is perfect for this task, but by default, it sorts in ascending order.

In this article, I’ll show you two simple ways to use np.argsort() to sort in descending order. Whether you’re analyzing stock prices, test scores, or sales data, these methods will help you quickly rank your data from highest to lowest.

NumPy’s argsort()

Before we get into the descending order techniques, let’s understand what argsort() does.

The argsort() function returns the indices that would sort an array. In simpler terms, it tells you the positions of elements if they were sorted.

For example, if we have an array [3, 1, 2], the argsort() would return [1, 2, 0] because the element at index 1 (which is 1) should come first in a sorted array, followed by the element at index 2 (which is 2), and finally the element at index 0 (which is 3).

By default, argsort() arranges in ascending order, which is often not what we want when ranking data.

Read Copy Elements from One List to Another in Python

Np.argsort in Descending Order in Python

Let me show you two methods to get the descending order with argsort() in Python

Method 1 – Use Negative Array Values

The simplest way to get descending order with argsort() in Python is to negate your array values before sorting. When we put a minus sign in front of an array, it reverses the order when sorted.

Here’s how to do it:

import numpy as np

# Sample data: NBA player points per game
player_points = np.array([28.5, 30.1, 25.7, 32.4, 27.3])

# Get indices that would sort in descending order
descending_indices = np.argsort(-player_points)

print("Original points:", player_points)
print("Indices for descending order:", descending_indices)
print("Points in descending order:", player_points[descending_indices])

Output:

Original points: [28.5 30.1 25.7 32.4 27.3]
Indices for descending order: [3 1 0 4 2]
Points in descending order: [32.4 30.1 28.5 27.3 25.7]

I executed the above example code and added the screenshot below.

numpy argsort descending

In this example, the player with 32.4 points (at index 3) is now first, followed by the player with 30.1 points, and so on.

This method is clean and concise, but it works by temporarily creating a negated copy of your array.

Check out the np.count() function in Python

Method 2 – Use Array Slicing with [::-1]

Another elegant approach is to first get the indices in ascending order and then reverse them using Python’s slice notation [::-1].

Here’s how to implement this method:

import numpy as np

# Sample data: S&P 500 stock prices
stock_prices = np.array([145.86, 327.42, 178.53, 267.97, 205.11])

# Get indices for ascending order
ascending_indices = np.argsort(stock_prices)

# Reverse the indices to get descending order
descending_indices = ascending_indices[::-1]

print("Original prices:", stock_prices)
print("Indices for descending order:", descending_indices)
print("Prices in descending order:", stock_prices[descending_indices])

Output:

Original prices: [145.86 327.42 178.53 267.97 205.11]
Indices for descending order: [1 3 4 2 0]
Prices in descending order: [327.42 267.97 205.11 178.53 145.86]

I executed the above example code and added the screenshot below.

numpy argsort

This method is particularly useful when you also need the ascending order indices in your code, as you get both with this approach.

Read Convert the DataFrame to a NumPy Array Without Index in Python

Real-World Example: Analyze Test Scores

Let’s use both methods in a practical example where we analyze student test scores:

import numpy as np

# Sample data: Student test scores (out of 100)
student_names = np.array(['Emma', 'Noah', 'Olivia', 'Liam', 'Sophia'])
test_scores = np.array([85, 92, 78, 96, 88])

# Method 1: Using negative array
top_students_indices = np.argsort(-test_scores)

# Display the results in a leaderboard
print("Class Leaderboard:")
for rank, idx in enumerate(top_students_indices, 1):
    print(f"{rank}. {student_names[idx]} - {test_scores[idx]}")

# Method 2: Using array slicing
# Let's say we want to find the bottom 3 students who need extra help
bottom_students_indices = np.argsort(test_scores)[:3]

print("\nStudents who might need additional support:")
for idx in bottom_students_indices:
    print(f"{student_names[idx]} - {test_scores[idx]}")

Output:

Class Leaderboard:
1. Liam - 96
2. Noah - 92
3. Sophia - 88
4. Emma - 85
5. Olivia - 78

Students who might need additional support:
Olivia - 78
Emma - 85
Sophia - 88

This example shows how you can use both methods effectively in real-world scenarios.

Check out Copy a NumPy Array to the Clipboard through Python

Performance Considerations

Both methods are efficient for most applications, but there are slight differences:

  1. The negative array method (np.argsort(-array)) creates a temporary copy of your array with negated values, which might matter for very large arrays.
  2. The array slicing method (np.argsort(array)[::-1]) first sorts in ascending order and then reverses the indices, which involves two steps.

For most practical applications, the performance difference is negligible, and you should choose the method that makes your code more readable.

When to Use argsort() in Descending Order

Using argsort() in descending order is particularly useful when:

  1. You need to maintain the original data, but access it in sorted order
  2. You want to find the top N items in a dataset
  3. You need to rank items from best to worst
  4. You’re creating leaderboards or prioritized lists

Read NumPy Divide Array by Scalar in Python

One-liner Method for Descending argsort()

If you prefer concise code, you can combine the operation into a one-liner:

descending_indices = np.argsort(array)[::-1]  # Method 2
# OR
descending_indices = np.argsort(-array)       # Method 1

I’ve found both approaches equally useful in different contexts, so choose the one that best fits your coding style.

It’s worth noting that NumPy also offers the option to specify the sort direction, but surprisingly, this feature isn’t available for argsort(), only for the regular sort() function.

I hope you found this guide helpful! In this tutorial, I have explained two methods, such as using negative array values and using array slicing with[::-1]. I also covered a real-world example, performance considerations, when to use argsort() in Descending Order, and

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.