1. Quick Overview
These NumPy functions are essential for sorting arrays, locating positions of specific values, filtering data conditionally, and working with multi-dimensional datasets.
| Function | Purpose | Returns |
|---|---|---|
np.sort() |
Sorts array values | Sorted array |
np.argsort() |
Finds indices that would sort an array | Index array |
np.lexsort() |
Sorts using multiple keys | Index array |
np.argmax() |
Finds index of maximum value | Index or indices |
np.argmin() |
Finds index of minimum value | Index or indices |
np.nonzero() |
Finds indices of nonzero elements | Tuple of index arrays |
np.where() |
Selects values or locates indices based on condition | Indices or selected values |
np.extract() |
Extracts values matching a condition | 1D array |
import numpy as np
2. np.sort() — Sort Array Elements
Purpose: Arrange array values in ascending or descending order.
Syntax and Arguments
| Argument | Meaning |
|---|---|
a |
Input array to be sorted. |
axis |
Axis along which to sort. Default is -1 (along the last axis). Pass None to sort a flattened copy. |
kind |
Sorting algorithm: 'quicksort' (default), 'mergesort', 'heapsort', or 'stable'. |
order |
For structured arrays, specifies field names to sort by. |
Practical 1: Sort a 1D Array
Output:
Step-by-Step Observation
- The original array contains unsorted marks.
np.sort()returns a new array arranged in ascending order.- The original array remains unchanged (it is not sorted in-place):
print(marks) # [75 45 90 60 85]
Practical 2: Descending Order
NumPy's sort() does not have a reverse=True parameter. Instead, sort and reverse the result using slice step [::-1]:
Output:
Practical 3: Sorting a 2D Array
You can control sorting direction using the axis parameter:
Output:
3. np.argsort() — Get Indices that Sort an Array
Purpose: Find the positions (indices) of elements in the order that would sort the array.
np.sort()returns the sorted values.np.argsort()returns the indices that arrange the values in sorted order.
Practical 1: Sort Indices of Student Marks
Output:
| Original Index | Mark |
|---|---|
| 0 | 75 |
| 1 | 45 (Smallest) |
| 2 | 90 (Largest) |
| 3 | 60 |
| 4 | 85 |
The sorted marks are 45, 60, 75, 85, 90. Their original indices are 1, 3, 0, 4, 2.
You can use these indices to index back into the array to get the sorted values:
Practical 2: Descending Order Using argsort()
Output:
Practical 3: argsort() with a 2D Array
Output:
4. np.lexsort() — Sort Using Multiple Keys
Purpose: Sort records using two or more columns (keys), such as sorting students by Department, and then by Marks within each department.
Critical Rule for lexsort:
The LAST key passed is the primary sorting key! Earlier keys in the tuple act as secondary tie-breakers.
Practical 1: Sort Students by Department, then Marks
Output:
How It Works
departmentis the primary key because it is last in(marks, department).- Departments are sorted alphabetically:
CS, thenIT. - Within each department,
marksbreak ties and sort ascending. - The returned index array is applied across all companion arrays.
Practical 2: Sort by Marks First, then Names
To sort primarily by marks, pass marks as the last key: (names, marks):
Output:
5. np.argmax() — Find Index of Maximum Value
Purpose: Return the index position of the largest element in the array.
Practical 1: Find the Highest Mark
Output:
Practical 2: Find Maximum Across Rows or Columns in 2D
Output:
np.argmax() returns the first occurrence.
6. np.argmin() — Find Index of Minimum Value
Purpose: Return the index position of the smallest element in the array.
Practical 1: Find the Lowest Mark
Output:
Practical 2: Find Minimum Indices in a 2D Array
Output:
7. np.nonzero() — Find Indices of Nonzero Elements
Purpose: Return the indices of all elements that are not equal to zero. In NumPy, 0, 0.0, and False are treated as zero; all other numbers and True are treated as nonzero.
Practical 1: Nonzero Elements in a 1D Array
Output:
Practical 2: nonzero() with a 2D Array
For a 2D array, nonzero() returns a tuple of two arrays: row coordinates and column coordinates:
Output:
Elements are at coordinates: (0, 1) → 10, (1, 0) → 20, and (1, 2) → 30.
8. np.where() — Conditional Search and Selection
np.where() has two distinct forms:
- Single argument (condition only): Returns the indices where the condition evaluates to
True. - Three arguments (condition, x, y): Returns elements chosen from
xwhere condition is true, and fromywhere false.
Practical 1: Finding Indices Matching a Condition
Output:
Practical 2: Categorizing Data with (condition, x, y)
Output:
Practical 3: Replacing Values Conditionally
Replace prices below 150 with 0, leaving other prices as they are:
Output:
9. np.extract() — Extract Elements Matching Condition
Purpose: Return a 1-dimensional array containing only the elements of an array that satisfy a Boolean condition.
Practical 1: Extract Passing Marks
Output:
Practical 2: Extracting from a 2D Array
Output:
np.extract() always flattens and returns a 1-dimensional array.
10. Quick Reference & Important Differences
| Requirement | Function | Code Example |
|---|---|---|
| Get sorted values | np.sort() |
np.sort(a) |
| Get indices for sorting | np.argsort() |
np.argsort(a) |
| Sort using multiple keys | np.lexsort() |
np.lexsort((marks, names)) |
| Find maximum index | np.argmax() |
np.argmax(a) |
| Find minimum index | np.argmin() |
np.argmin(a) |
| Find nonzero indices | np.nonzero() |
np.nonzero(a) |
| Find indices or choose conditionally | np.where() |
np.where(a > 50, 'High', 'Low') |
| Extract values matching condition | np.extract() |
np.extract(a > 50, a) |
Sorting and Searching Quiz
Test your understanding of NumPy sorting and searching functions. Click an option to see instant feedback.