Sorting Arrays & Extracting Indices (np.sort vs np.argsort)
Sorting Arrays: np.sort() vs np.argsort()
Sorting data is a core algorithmic primitive in numerical computing. In scientific pipelines, sorting enables ranking, percentile calculation, quantile binning, nearest-neighbor searches, and ordering multi-column tables.
NumPy provides two complementary sorting paradigms:
- Direct Sorting (
np.sort()/arr.sort()): Reorders and returns the actual values. - Indirect Sorting (
np.argsort()): Returns the indices that would sort the array, enabling simultaneous sorting of multiple associated datasets.
1. Direct Sorting: Function vs In-Place Method
np.sort(arr): Returns a sorted copy of the array, leaving the original array completely untouched.arr.sort(): Sorts the array in-place directly within its existing memory buffer, returningNone.
2. Multi-Dimensional Sorting Along Axes
When sorting multi-dimensional arrays, you can specify the target axis along which elements are ordered:
Output:
3. Indirect Sorting with np.argsort()
In real-world data science, you rarely sort a single isolated column. Instead, you have parallel arrays—such as employee names, salaries, and performance ratings—and sorting by salary must reorder the names and ratings in identical order.
np.argsort() returns the array of integer indices that put the array into sorted order:
Sorting in Descending Order:
To sort in descending order (highest first), slice the resulting indices with [::-1]:
4. Multi-Key Lexicographical Sorting with np.lexsort()
When sorting by multiple columns (e.g. sort primarily by Surname, and secondarily by First Name):
np.lexsort(): The keys are passed as a tuple, and the LAST key in the tuple is the PRIMARY sort key!Output:
Multiple Choice Questions
1. What is the return value of arr.sort()?
A. A new sorted array B. None (it sorts the array in-place) C. The sorted indices D. A boolean True Answer: B Explanation: The ndarray method arr.sort() sorts the existing memory buffer in-place and returns None. To get a new sorted copy without modifying the original, use np.sort(arr).
2. What does np.argsort(arr) return?
A. A sorted copy of the array elements B. An array of integer indices that would sort the array C. A boolean mask indicating which elements are in sorted order D. The median index of the array Answer: B Explanation: np.argsort() performs an indirect sort, returning an array of integer indices corresponding to the elements in ascending sorted order.
3. Given salaries = np.array([50000, 30000, 80000]), what is the output of np.argsort(salaries)?
A. array([30000, 50000, 80000]) B. array([1, 0, 2]) C. array([2, 0, 1]) D. array([0, 1, 2]) Answer: B Explanation: 30000 is at index 1 (smallest), 50000 is at index 0 (middle), and 80000 is at index 2 (largest). Thus, the ascending indices are [1, 0, 2].
4. In np.lexsort((col_b, col_a)), which column acts as the primary sort key?
A. col_b B. col_a C. Both columns equally D. Randomly depending on data types Answer: B Explanation: In NumPy's lexsort(), the keys are evaluated in reverse order: the last array in the passed tuple (col_a) is the primary sort key, while preceding arrays break ties.
5. How can you sort a 1D array in descending order using np.sort()?
A. np.sort(arr, reverse=True) B. np.sort(arr)[::-1] C. np.sort_desc(arr) D. arr.sort(order='desc') Answer: B Explanation: np.sort() does not possess a reverse keyword argument. The standard, idiomatic NumPy technique is to sort ascending and reverse using slice step -1: np.sort(arr)[::-1].
Searching & Counting (argmax, argmin, nonzero, count_nonzero)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.