Sorting and Searching in NumPy
Sorting and searching are essential operations when working with numerical data. NumPy provides fast and easy-to-use functions to arrange data and locate values efficiently.
In this lesson, you will learn how to sort arrays, find indexes of values, and perform conditional searches.
Sample Dataset
We will use the following dataset for all examples.
import numpy as np
data = np.array([42, 15, 88, 23, 64, 10, 37])
print(data)
This array represents unordered numeric values.
Sorting an Array
The np.sort() function returns a sorted copy of the array.
sorted_data = np.sort(data)
print(sorted_data)
Output:
[10 15 23 37 42 64 88]
The original array remains unchanged.
Sorting in Descending Order
To sort in descending order, reverse the sorted array.
descending = np.sort(data)[::-1]
print(descending)
Output:
[88 64 42 37 23 15 10]
Sorting Multidimensional Arrays
NumPy can sort arrays along specific axes.
matrix = np.array([
[5, 2, 9],
[1, 7, 3]
])
print(np.sort(matrix))
Output:
[[2 5 9]
[1 3 7]]
Each row is sorted independently.
Finding Index Positions
The np.argsort() function returns the indexes that would sort the array.
indexes = np.argsort(data)
print(indexes)
Output:
[5 1 3 6 0 4 2]
These indexes show the order needed to sort the array.
Searching for Specific Values
Use np.where() to find indexes that match a condition.
positions = np.where(data > 40)
print(positions)
Output:
(array([0, 2, 4]),)
This means values greater than 40 are located at indexes 0, 2, and 4.
Finding Minimum and Maximum Index
You can locate the position of the smallest and largest values.
min_index = np.argmin(data)
max_index = np.argmax(data)
print(min_index)
print(max_index)
Output:
5
2
These indexes point to the smallest and largest values in the array.
Real-World Example
Imagine this dataset represents daily sales:
- Sorting → ranking sales days
- argmax → best-performing day
- argmin → lowest-performing day
- where → days crossing a target threshold
Sorting and searching help extract insights quickly from raw data.
Practice Exercise
Task
- Create a NumPy array with random numbers
- Sort it in ascending and descending order
- Find the index of the largest value
- Locate all values greater than a chosen number
What’s Next?
In the next lesson, you will learn about Stacking Arrays in NumPy, which allows combining multiple arrays efficiently.