Where np.sort() gives you the sorted values, np.argsort() gives you the order — a set of indices such that indexing the original array with them reproduces np.sort()'s result. This is especially useful for sorting several related arrays in the same consistent order based on values in just one of them: compute the sort order once with argsort() on the key array, then apply that same index order to every related array via fancy indexing.
1Understanding np.argsort()
Where np.sort() gives you the sorted values, np.argsort() gives you the order — a set of indices such that indexing the original array with them reproduces np.sort()'s result. This is especially useful for sorting several related arrays in the same consistent order based on values in just one of them: compute the sort order once with argsort() on the key array, then apply that same index order to every related array via fancy indexing.
Use np.argsort() when you need to sort one array by the values in another — like sorting a list of names by a corresponding list of scores — by computing the index order once with argsort() and applying it to both arrays with fancy indexing.
import numpy as np
arr = np.array([3, 1, 4, 1, 5])
print(np.argsort(arr))2Practical Example
Here is a real-world application of np.argsort() showing how it is used in production NumPy code.
import numpy as np
names = np.array(["Charlie", "Alice", "Bob"])
scores = np.array([85, 92, 78])
order = np.argsort(scores)
print(names[order])3Best Practices
Follow these guidelines when working with np.argsort():
1. Use argsort() to sort several related arrays consistently based on one of them, instead of manually zipping, sorting, and unzipping
2. Reverse an ascending argsort() result with a negative slice, or negate the array before sorting, to get a descending order
3. Use np.sort() directly instead when you only need the sorted values and don't need to apply that same order to other data
Tip: Use np.argsort() when you need to sort one array by the values in another — like sorting a list of names by a corresponding list of scores — by computing the index order once with argsort() and applying it to both arrays with fancy indexing.
import numpy as np
arr = np.array([3, 1, 4, 1, 5])
print(np.argsort(arr))