Sort the rows of a NumPy array by a primary and a secondary key with np.lexsort
Quick Overview
Sort the rows of a 2-D NumPy array by a primary column and then a secondary column using np.lexsort, keeping ties stable. It tests the key order lexsort expects, applying an index permutation to whole rows, stable sorting, and descending keys.
Sort the rows of a NumPy array by a primary and a secondary key with np.lexsort
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 2-D NumPy array `arr` of records, where column 0 is the primary key and column 1 is the secondary key, return the full rows sorted by the primary key ascending, with ties broken by the secondary key ascending.
The function must meet these requirements:
- Use `np.lexsort` with the keys `(secondary, primary)` (the last key is the primary one), then index `arr` with the resulting permutation.
- Return rows, not indices.
- Rows with equal composite keys keep their original relative order (the sort is stable).
```python
arr = np.array([
[2, 9],
[1, 5],
[2, 3],
[1, 8],
])
sort_by_two_keys(arr)
# array([[1, 5],
# [1, 8],
# [2, 3],
# [2, 9]])
```
The two rows with primary key 1 are ordered by their secondary keys 5 and 8, and the two rows with primary key 2 by 3 and 9.
```hint From order to rows
`np.lexsort` returns a permutation of row positions. Think about which indexing operation applies that permutation to whole rows at once.
```
### What a Strong Answer Covers
- The key order `np.lexsort` expects and why the primary key goes last.
- Turning the index permutation into reordered rows without scrambling columns.
- Why rows that tie on both keys keep their input order.
- Time and space complexity.
### Follow-up Questions
- How would you make one key sort descending while the other stays ascending?
- When would you prefer a structured array or `np.sort` with `order=` over `lexsort`?
- How would you sort by every column, with column 0 the most significant?
Overview: Sort the rows of a 2-D NumPy array by a primary column and then a secondary column using np.lexsort, keeping ties stable. It tests the key order lexsort expects, applying an index permutation to whole rows, stable sorting, and descending keys.
Given a 2-D NumPy array arr of records, where column 0 is the primary key and column 1 is the secondary key, return the full rows sorted by the primary key ascending, with ties broken by the secondary key ascending.
The function must meet these requirements:
Use
np.lexsort
with the keys
(secondary, primary)
(the last key is the primary one), then index
arr
with the resulting permutation.
Return rows, not indices.
Rows with equal composite keys keep their original relative order (the sort is stable).