How to get indices of a sorted array in Python
Quickly obtain sorted array indices in Python using numpy.argsort()
:
np.argsort()
yields indices to arrange an array
in ascending order. In this case, it turns [3, 1, 2]
into [1, 2, 3]
, as indicated by the indices [1, 2, 0]
.
No NumPy? No problem!
Python's built-in functions got you covered when NumPy isn't available. For instance, sorted(enumerate(list), key=lambda x: x[1])
can do the job, packaging index-value pairs, sorted by value:
If enumerate list comprehension doesn't tickle your fancy, sorted(range(len(list)), key=list.__getitem__)
offers a simpler mechanism, connecting you straight to the indices:
Advanced sorting techniques that break ties beautifully
Sometimes, duels aren't your thing. To solve fights AKA ties, we can maintain the original order in the sorted array through stable sorting. Here's how to retrieve the indices for a stable sort:
Also, for tackling complex comparisons or handling custom objects, key
parameters can be combined with bespoke functions.
Spicing up the order
For those who enjoy chaos - Descending order
Let's shake things up a bit! To sort in a descending order, simply append a minus sign (-
) to the sort key:
Dealing with multi-dimensional arrays
For 2D arrays or matrices, specify the axis
to control whether you want the sort to occur along rows or columns:
Working with complex data
For complex comparisons or custom objects, the attrgetter
or itemgetter
from the operator
module provide efficient sorting:
Efficiency first
Perks of picking perfplot for performance analysis
A tool like perfplot
can confirm how different methods perform. Through its exciting graphs, you can analyze how np.argsort()
fares against other sorting techniques.
Ponderings for large datasets
For larger datasets, algorithmic complexity comes into play. While argsort
from NumPy is fairly optimized, Python's native methods with list comprehensions might want to take the back seat for these!
Was this article helpful?