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
Common Import for all examples: import numpy as np

2. np.sort() — Sort Array Elements

Purpose: Arrange array values in ascending or descending order.

Syntax and Arguments

np.sort(a, axis=-1, kind=None, order=None)
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

import numpy as np marks = np.array([75, 45, 90, 60, 85]) result = np.sort(marks) print(result)

Output:

[45 60 75 85 90]
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]:

marks = np.array([75, 45, 90, 60, 85]) result = np.sort(marks)[::-1] print(result)

Output:

[90 85 75 60 45]

Practical 3: Sorting a 2D Array

You can control sorting direction using the axis parameter:

a = np.array([[30, 10, 20], [90, 50, 70]]) print("axis=0 (sort vertically down each column):") print(np.sort(a, axis=0)) print("\naxis=1 (sort horizontally across each row):") print(np.sort(a, axis=1)) print("\naxis=None (flatten all elements into a 1D sorted array):") print(np.sort(a, axis=None))

Output:

axis=0 (sort vertically down each column): [[30 10 20] [90 50 70]] axis=1 (sort horizontally across each row): [[10 20 30] [50 70 90]] axis=None (flatten all elements into a 1D sorted array): [10 20 30 50 70 90]

3. np.argsort() — Get Indices that Sort an Array

Purpose: Find the positions (indices) of elements in the order that would sort the array.

Remember the difference:
  • 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

marks = np.array([75, 45, 90, 60, 85]) result = np.argsort(marks) print("Indices that sort marks:", result)

Output:

Indices that sort marks: [1 3 0 4 2]
Original Index Mark
075
145 (Smallest)
290 (Largest)
360
485

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:

indices = np.argsort(marks) print(marks[indices]) # [45 60 75 85 90]

Practical 2: Descending Order Using argsort()

marks = np.array([75, 45, 90, 60, 85]) indices = np.argsort(marks)[::-1] print("Descending indices:", indices) print("Descending marks:", marks[indices])

Output:

Descending indices: [2 4 0 3 1] Descending marks: [90 85 75 60 45]

Practical 3: argsort() with a 2D Array

a = np.array([[30, 10, 20], [90, 50, 70]]) print("axis=1 (indices within each row):") print(np.argsort(a, axis=1)) print("\naxis=0 (indices within each column):") print(np.argsort(a, axis=0)) print("\naxis=None (indices into the flattened array):") print(np.argsort(a, axis=None))

Output:

axis=1 (indices within each row): [[1 2 0] [1 2 0]] axis=0 (indices within each column): [[0 0 0] [1 1 1]] axis=None (indices into the flattened array): [1 2 0 4 5 3]
Real-world Use: Rank students, candidates, or search results by score while keeping their original database IDs synchronized!

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

import numpy as np names = np.array(["Amit", "Neha", "Raj", "Kiran", "Priya"]) department = np.array(["IT", "CS", "IT", "CS", "IT"]) marks = np.array([80, 90, 70, 85, 95]) # Pass (secondary_key, primary_key) -> (marks, department) indices = np.lexsort((marks, department)) print("Sorted Indices:", indices) print("Names:", names[indices]) print("Department:", department[indices]) print("Marks:", marks[indices])

Output:

Sorted Indices: [1 3 2 0 4] Names: ['Neha' 'Kiran' 'Raj' 'Amit' 'Priya'] Department: ['CS' 'CS' 'IT' 'IT' 'IT'] Marks: [85 90 70 80 95]
How It Works
  1. department is the primary key because it is last in (marks, department).
  2. Departments are sorted alphabetically: CS, then IT.
  3. Within each department, marks break ties and sort ascending.
  4. 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):

indices = np.lexsort((names, marks)) print("Names:", names[indices]) print("Marks:", marks[indices])

Output:

Names: ['Raj' 'Amit' 'Kiran' 'Neha' 'Priya'] Marks: [70 80 85 90 95]

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

marks = np.array([75, 45, 90, 60, 85]) index = np.argmax(marks) print("Index of maximum:", index) print("Maximum mark:", marks[index])

Output:

Index of maximum: 2 Maximum mark: 90

Practical 2: Find Maximum Across Rows or Columns in 2D

a = np.array([[10, 50, 30], [90, 40, 70]]) print("axis=0 (max index per column):", np.argmax(a, axis=0)) print("axis=1 (max index per row):", np.argmax(a, axis=1))

Output:

axis=0 (max index per column): [1 0 1] axis=1 (max index per row): [1 0]
Note on duplicates: If the maximum value occurs multiple times, 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

marks = np.array([75, 45, 90, 60, 85]) index = np.argmin(marks) print("Index of minimum:", index) print("Minimum mark:", marks[index])

Output:

Index of minimum: 1 Minimum mark: 45

Practical 2: Find Minimum Indices in a 2D Array

a = np.array([[10, 50, 30], [90, 40, 70]]) print("axis=0 (min index per column):", np.argmin(a, axis=0)) print("axis=1 (min index per row):", np.argmin(a, axis=1))

Output:

axis=0 (min index per column): [0 1 0] axis=1 (min index per row): [0 1]
Real-world Use: Finding lowest product price on an e-commerce platform, minimum daily temperature, or the shortest delivery route.

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

a = np.array([10, 0, 20, 0, 30]) result = np.nonzero(a) print("Indices:", result) print("Nonzero values:", a[result])

Output:

Indices: (array([0, 2, 4]),) Nonzero values: [10 20 30]

Practical 2: nonzero() with a 2D Array

For a 2D array, nonzero() returns a tuple of two arrays: row coordinates and column coordinates:

a = np.array([[0, 10, 0], [20, 0, 30]]) result = np.nonzero(a) print("Row & Column Indices:\n", result) print("\nExtracted Values:", a[result])

Output:

Row & Column Indices: (array([0, 1, 1]), array([1, 0, 2])) Extracted Values: [10 20 30]

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:

  1. Single argument (condition only): Returns the indices where the condition evaluates to True.
  2. Three arguments (condition, x, y): Returns elements chosen from x where condition is true, and from y where false.

Practical 1: Finding Indices Matching a Condition

marks = np.array([45, 75, 30, 90, 60]) result = np.where(marks > 60) print("Indices where marks > 60:", result) print("Matching values:", marks[result])

Output:

Indices where marks > 60: (array([1, 3]),) Matching values: [75 90]

Practical 2: Categorizing Data with (condition, x, y)

marks = np.array([45, 75, 30, 90, 60]) result = np.where(marks >= 60, "Pass", "Fail") print(result)

Output:

['Fail' 'Pass' 'Fail' 'Pass' 'Pass']

Practical 3: Replacing Values Conditionally

Replace prices below 150 with 0, leaving other prices as they are:

prices = np.array([100, 250, 50, 400, 150]) result = np.where(prices < 150, 0, prices) print(result)

Output:

[ 0 250 0 400 150]

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

marks = np.array([45, 75, 30, 90, 60]) result = np.extract(marks >= 60, marks) print(result)

Output:

[75 90 60]

Practical 2: Extracting from a 2D Array

a = np.array([[10, 70, 30], [90, 40, 80]]) # Extracts elements > 50 result = np.extract(a > 50, a) print(result)

Output:

[70 90 80]
Even though the input is 2D, 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.

1. What is the fundamental difference between np.sort(a) and np.argsort(a)?
A) np.sort() sorts in descending order; np.argsort() sorts ascending
B) np.sort() returns sorted values; np.argsort() returns the indices that would sort the array
C) np.argsort() modifies the array in-place; np.sort() returns a copy
D) They are exact synonyms
2. In np.lexsort((col_A, col_B)), which column serves as the PRIMARY sorting key?
A) col_A
B) col_B (the last column in the tuple)
C) Both simultaneously
D) Whichever has larger values
3. What is the output of np.argmax(np.array([10, 50, 50, 20]))?
A) 1 (first occurrence of the maximum value)
B) 2 (last occurrence of the maximum value)
C) [1, 2]
D) 50
4. What does np.where(arr > 0, 1, -1) do?
A) Returns only indices where arr > 0
B) Replaces positive values with 1, and zero or negative values with -1
C) Deletes negative numbers
D) Raises a ValueError
5. What is the output dimension of np.extract() when applied to a 2D array?
A) Always a 2D array
B) Always a 1D array
C) A scalar
D) A tuple of coordinate arrays