0
0
NumPydata~5 mins

np.argsort() for sort indices in NumPy

Choose your learning style9 modes available
Introduction

We use np.argsort() to find the order of elements that would sort an array. It tells us the positions to rearrange the data instead of sorting the data itself.

When you want to sort data but keep track of original positions.
When you need to reorder one array based on the sorted order of another array.
When you want to find rankings or positions of elements in sorted order.
When you want to sort data without changing the original array.
Syntax
NumPy
np.argsort(a, axis=-1, kind='quicksort', order=None)

a is the input array to find sort indices for.

The result is an array of indices that sort a.

Examples
This finds indices that sort the array [3, 1, 2]. The output shows positions of elements in ascending order.
NumPy
import numpy as np
arr = np.array([3, 1, 2])
indices = np.argsort(arr)
print(indices)
This finds sort indices along each row of a 2D array.
NumPy
arr = np.array([[3, 1], [2, 4]])
indices = np.argsort(arr, axis=1)
print(indices)
This uses argsort to sort the array by rearranging elements using the indices.
NumPy
arr = np.array([3, 1, 2])
sorted_arr = arr[np.argsort(arr)]
print(sorted_arr)
Sample Program

This program shows how to get sort indices with np.argsort(), use them to sort the array, and find the rank (position) of each element in the sorted order.

NumPy
import numpy as np

# Original array
arr = np.array([50, 20, 30, 10, 40])

# Get indices that would sort the array
sort_indices = np.argsort(arr)
print('Sort indices:', sort_indices)

# Use indices to sort the array
sorted_arr = arr[sort_indices]
print('Sorted array:', sorted_arr)

# Example: Find rank of each element
ranks = np.empty_like(sort_indices)
ranks[sort_indices] = np.arange(len(arr))
print('Ranks of elements:', ranks)
OutputSuccess
Important Notes

np.argsort() returns indices, not sorted values.

You can use the indices to reorder the original array or related arrays.

For multidimensional arrays, specify axis to sort along rows or columns.

Summary

np.argsort() gives the order of indices to sort an array.

Use it to sort arrays without changing the original data directly.

It helps find rankings and reorder related data consistently.