np.lexsort() takes a sequence of key arrays, all the same length, and returns the indices that would sort them together, similar in concept to a SQL 'ORDER BY column1, column2' query — but somewhat counterintuitively, the last array in the sequence is the primary sort key, and earlier arrays are used as tie-breakers, in order, which is the opposite of what many people expect from the argument order. This is useful for sorting by multiple criteria at once, like sorting a dataset first by category and then by price within each category.
1Understanding np.lexsort()
np.lexsort() takes a sequence of key arrays, all the same length, and returns the indices that would sort them together, similar in concept to a SQL 'ORDER BY column1, column2' query — but somewhat counterintuitively, the last array in the sequence is the primary sort key, and earlier arrays are used as tie-breakers, in order, which is the opposite of what many people expect from the argument order. This is useful for sorting by multiple criteria at once, like sorting a dataset first by category and then by price within each category.
Remember lexsort()'s key order is reversed from what feels intuitive — the last array passed is the primary sort key, and earlier arrays only break ties, which is the opposite of typical 'first key is primary' expectations from something like SQL's ORDER BY.
import numpy as np
last_names = np.array(["Smith", "Jones", "Smith"])
first_names = np.array(["Bob", "Alice", "Ann"])
order = np.lexsort((first_names, last_names))
print(order)2Practical Example
Here is a real-world application of np.lexsort() showing how it is used in production NumPy code.
import numpy as np
last_names = np.array(["Smith", "Jones", "Smith"])
first_names = np.array(["Bob", "Alice", "Ann"])
order = np.lexsort((first_names, last_names))
print(last_names[order])
print(first_names[order])3Best Practices
Follow these guidelines when working with np.lexsort():
1. Pass the primary sort key last in the keys sequence to lexsort(), and secondary/tie-breaking keys before it, remembering the reversed order convention
2. Use lexsort() instead of a custom multi-key comparator when sorting by several criteria at once
3. Apply the resulting index array to every related dataset column via fancy indexing, the same pattern as with argsort()
Tip: Remember lexsort()'s key order is reversed from what feels intuitive — the last array passed is the primary sort key, and earlier arrays only break ties, which is the opposite of typical 'first key is primary' expectations from something like SQL's ORDER BY.
import numpy as np
last_names = np.array(["Smith", "Jones", "Smith"])
first_names = np.array(["Bob", "Alice", "Ann"])
order = np.lexsort((first_names, last_names))
print(order)