🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEnumpy

numpy Documentation

LOADING ENGINE...

np.lexsort()

AI & DATA SCIENCE // np-lexsort

np.lexsort() performs an indirect sort using multiple keys, sorting primarily by the last key given, with earlier keys used to break ties.

Syntax

np.lexsort(keys)

Deep Dive Course

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.

editor.html
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)
localhost:3000

2Practical Example

Here is a real-world application of np.lexsort() showing how it is used in production NumPy code.

editor.html
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])
localhost:3000

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.

editor.html
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)
localhost:3000

Examples

Example 01Basic Usage
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)
Example 02Advanced Example
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])

Best Practices

  • Pass the primary sort key last in the keys sequence to lexsort(), and secondary/tie-breaking keys before it, remembering the reversed order convention
  • Use lexsort() instead of a custom multi-key comparator when sorting by several criteria at once
  • Apply the resulting index array to every related dataset column via fancy indexing, the same pattern as with argsort()

Interview Question

Why does calling lexsort with first_names listed before last_names sort primarily by last_names, even though first_names comes first in the arguments?

Hint: Think about lexsort()'s specific, somewhat unusual argument-order convention.

lexsort() treats the last array in its input sequence as the primary sort key and every array before it as progressively lower-priority tie-breakers, which is the reverse of what many people would intuitively expect from argument order. So passing first_names then last_names means last_names is actually the primary key determining the overall order, while first_names only decides the relative order of entries that share the exact same last name — this reversed convention is a well-known, if counterintuitive, quirk of lexsort()'s design.

Exercises

MediumPractice using np.lexsort() in a real scenario.
View Solution
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)

Frequently Asked Questions

Why does calling lexsort with first_names listed before last_names sort primarily by last_names, even though first_names comes first in the arguments?

lexsort() treats the last array in its input sequence as the primary sort key and every array before it as progressively lower-priority tie-breakers, which is the reverse of what many people would intuitively expect from argument order. So passing first_names then last_names means last_names is actually the primary key determining the overall order, while first_names only decides the relative order of entries that share the exact same last name — this reversed convention is a well-known, if counterintuitive, quirk of lexsort()'s design.

Related Functions

np-argsortnp-sortnp-searchsorted