Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

NumPy Sorting and Searching Arrays

NumPy provides efficient functions for sorting array elements and searching for specific values or positions. Sorting helps organize numerical data, while searching helps locate matching elements, insertion positions, and extreme values. In this lesson, you will learn ascending and descending sorting, multidimensional sorting, index-based sorting, binary search, and practical searching techniques.

1. Introduction to Sorting Arrays

Sorting arranges array elements in a specific order. Numerical arrays are commonly sorted in ascending order, from smallest to largest. Sorting can make data easier to inspect, compare, and analyze.

import numpy as np values = np.array([45, 12, 89, 23, 67, 34]) sorted_values = np.sort(values) print("Original array:", values) print("Sorted array:", sorted_values)

Output:

Original array: [45 12 89 23 67 34] Sorted array: [12 23 34 45 67 89]

The np.sort() function returns a sorted copy of the array. The original array remains unchanged.

Benefits of Sorting

  • Organizes numerical values in ascending or descending order.
  • Makes minimum and maximum values easier to inspect.
  • Helps prepare data for binary search.
  • Supports ranking and data analysis tasks.

2. Sorting in Ascending and Descending Order

By default, np.sort() sorts numerical values in ascending order. To obtain descending order, reverse the sorted result using slicing.

import numpy as np scores = np.array([72, 95, 61, 88, 79]) ascending = np.sort(scores) descending = np.sort(scores)[::-1] print("Ascending:", ascending) print("Descending:", descending)

Output:

Ascending: [61 72 79 88 95] Descending: [95 88 79 72 61]
Tip: The slice [::-1] reverses the order of elements. Sorting first and then reversing is a simple way to create descending numerical order.

3. Understanding np.sort() and the axis Parameter

For a multidimensional array, the axis parameter controls the direction of sorting. By default, NumPy sorts along the last axis.

import numpy as np data = np.array([ [30, 10, 20], [90, 60, 80], [15, 45, 25] ]) print("Sort each row:") print(np.sort(data, axis=1)) print("Sort each column:") print(np.sort(data, axis=0))

Output:

Sort each row: [[10 20 30] [60 80 90] [15 25 45]] Sort each column: [[15 10 20] [30 45 25] [90 60 80]]
Expression Behavior
np.sort(data) Sorts along the last axis by default.
np.sort(data, axis=0) Sorts each column independently.
np.sort(data, axis=1) Sorts each row independently.
np.sort(data, axis=None) Sorts all elements and returns a flattened one-dimensional array.

4. Sorting Without Losing the Original Data

The np.sort() function returns a sorted copy. If you use the array method sort(), the existing array is sorted in place.

import numpy as np values = np.array([40, 10, 30, 20]) sorted_copy = np.sort(values) print("Original:", values) print("Sorted copy:", sorted_copy) values.sort() print("After in-place sorting:", values)

Output:

Original: [40 10 30 20] Sorted copy: [10 20 30 40] After in-place sorting: [10 20 30 40]
Important: Use np.sort(values) when you need to preserve the original ordering. Use values.sort() when modifying the original array is intended.

5. Sorting with Different Algorithms

NumPy supports different sorting algorithms. The kind parameter lets you select an algorithm when needed.

Algorithm General Description
quicksort A quick comparison-based sorting algorithm.
heapsort A comparison-based algorithm using a heap structure.
mergesort A stable sorting option supported by NumPy.
stable Requests a stable sort that preserves the relative order of equal keys.
import numpy as np values = np.array([50, 20, 40, 10, 30]) print(np.sort(values, kind="quicksort")) print(np.sort(values, kind="heapsort")) print(np.sort(values, kind="stable"))

Output:

[10 20 30 40 50] [10 20 30 40 50] [10 20 30 40 50]

All three examples produce the same numerical order. The algorithm choice affects implementation behavior and can matter for performance or stability requirements.

6. Sorting Indices with np.argsort()

Sometimes you need the positions that would sort an array rather than the sorted values themselves. The np.argsort() function returns these indices.

import numpy as np marks = np.array([78, 92, 65, 88, 74]) indices = np.argsort(marks) print("Sorted indices:", indices) print("Sorted marks:", marks[indices])

Output:

Sorted indices: [2 4 0 3 1] Sorted marks: [65 74 78 88 92]

The first sorted value, 65, originally appeared at index 2. The next value, 74, originally appeared at index 4. These positions are represented by the returned index array.

When Is argsort() Useful?

  • Ranking students by marks.
  • Ordering records according to a numerical score.
  • Reordering one array based on another array's values.
  • Finding the indices of the lowest or highest values.

7. Searching for Values with np.where()

The np.where() function can locate positions where a condition is true. It is useful for finding exact matches or identifying values that meet a threshold.

import numpy as np values = np.array([12, 25, 37, 25, 48, 25]) indices = np.where(values == 25) print("Matching indices:", indices[0]) print("Matching values:", values[indices])

Output:

Matching indices: [1 3 5] Matching values: [25 25 25]

Find Values Above a Threshold

import numpy as np temperatures = np.array([18, 26, 31, 22, 35, 29]) indices = np.where(temperatures > 28) print("Indices:", indices[0]) print("Values:", temperatures[indices])

Output:

Indices: [2 4 5] Values: [31 35 29]

8. Searching in Sorted Arrays with np.searchsorted()

The np.searchsorted() function finds an insertion position that keeps a sorted array in order. It uses binary-search logic and assumes the input array is sorted.

import numpy as np values = np.array([10, 20, 30, 40, 50]) position = np.searchsorted(values, 35) print("Insertion position:", position) updated = np.insert(values, position, 35) print("Updated array:", updated)

Output:

Insertion position: 3 Updated array: [10 20 30 35 40 50]

Left and Right Insertion Positions

import numpy as np values = np.array([10, 20, 20, 20, 30, 40]) left_position = np.searchsorted(values, 20, side="left") right_position = np.searchsorted(values, 20, side="right") print("Left position:", left_position) print("Right position:", right_position)

Output:

Left position: 1 Right position: 4

The left position is before the existing values equal to 20. The right position is after all of them.

Important: Do not use np.searchsorted() on an unsorted array unless you explicitly provide valid sorting-order information. Otherwise, the insertion position may not be meaningful.

9. Finding the Smallest and Largest Values

NumPy offers several ways to identify extreme values. The functions np.argmin() and np.argmax() return the positions of the minimum and maximum values.

import numpy as np sales = np.array([450, 720, 380, 910, 650, 840]) lowest_index = np.argmin(sales) highest_index = np.argmax(sales) print("Lowest sales:", sales[lowest_index]) print("Lowest index:", lowest_index) print("Highest sales:", sales[highest_index]) print("Highest index:", highest_index)

Output:

Lowest sales: 380 Lowest index: 2 Highest sales: 910 Highest index: 3

Find the Three Largest Values

The np.partition() function can place the smallest or largest values into their correct partition positions without fully sorting every element.

import numpy as np sales = np.array([450, 720, 380, 910, 650, 840]) three_largest = np.partition(sales, -3)[-3:] result = np.sort(three_largest)[::-1] print(result)

Output:

[910 840 720]

Partitioning does not sort every element. Sorting the selected three values afterward displays them in descending order.

10. Practical Project: Ranking Student Marks

In this project, we will sort student marks, find their ranking order, and identify the highest and lowest scores.

import numpy as np students = np.array(["Samadhan", "Pradnya", "Samiksha"]) marks = np.array([78, 95, 86]) ranking_indices = np.argsort(marks)[::-1] print("Student ranking:") for rank, index in enumerate(ranking_indices, start=1): print( rank, students[index], "- Marks:", marks[index] ) print("Highest mark:", np.max(marks)) print("Lowest mark:", np.min(marks))

Output:

Student ranking: 1 Pradnya - Marks: 95 2 Samiksha - Marks: 86 3 Samadhan - Marks: 78 Highest mark: 95 Lowest mark: 78

Project Learning Outcomes

  • Sort student marks in ascending order.
  • Use np.argsort() to get ranking indices.
  • Keep student names aligned with their corresponding marks.
  • Use np.max() and np.min() to identify extreme scores.

11. Common Mistakes and Best Practices

Confusing sort() and argsort()

np.sort() returns sorted values, whereas np.argsort() returns the indices that describe the sorted order.

Searching an Unsorted Array with searchsorted()

Ensure the input is sorted before using np.searchsorted(), or provide the appropriate sorter argument when working with an indirect ordering.

Overwriting the Original Array

np.sort() returns a sorted copy. The array method array.sort() modifies the original array in place.

Sorting the Wrong Axis

For multidimensional arrays, choose the axis according to whether you need to sort each row, each column, or the complete array.

Assuming Duplicate Values Have a Unique Position

A value may appear more than once. Use np.where() when you need every index satisfying a condition.

12. Practice Exercises

Exercise 1: Basic Sorting

Create an array containing [45, 12, 89, 23, 67, 34]. Sort it in ascending and descending order.

Exercise 2: Matrix Sorting

Create a 3 by 3 matrix and sort its rows using axis=1. Then sort its columns using axis=0.

Exercise 3: Sorting Indices

Use np.argsort() to find the indices that would sort a marks array. Use those indices to arrange student names by marks.

Exercise 4: Search for Values

Use np.where() to find every occurrence of a target value in an array.

Exercise 5: Insertion Position

Use np.searchsorted() to find the insertion position of 35 in a sorted array containing [10, 20, 30, 40, 50].

Exercise 6: Student Ranking

Create marks for Samadhan, Pradnya, and Samiksha. Print their ranking from highest to lowest using np.argsort().

Summary

In this lesson, you learned to sort NumPy arrays using np.sort(), control sorting direction with slicing, and sort multidimensional arrays along a selected axis. You also explored in-place sorting and index-based sorting with np.argsort().

You practiced locating values with np.where(), finding insertion positions with np.searchsorted(), and identifying extreme values with np.argmin() and np.argmax(). These techniques are useful for ranking, searching, and organizing numerical datasets.