NumPy Functions
Beyond basic arithmetic and array creation, NumPy provides a rich set of functions for sorting, searching, and summarizing data - tools you'll reach for constantly while preparing data for analysis.
Sorting Functions
import numpy as np
arr = np.array([5, 2, 8, 1, 9])
print(np.sort(arr)) # [1 2 5 8 9]
print(np.argsort(arr)) # [3 1 0 2 4] - indices that would sort the array
Searching Functions
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(np.where(arr > 25)) # (array([2, 3, 4]),) - indices matching condition
print(np.searchsorted(arr, 35)) # 3 - index where 35 would be inserted to keep order
Unique Values and Counting
import numpy as np
arr = np.array([1, 2, 2, 3, 3, 3, 4])
print(np.unique(arr)) # [1 2 3 4]
values, counts = np.unique(arr, return_counts=True)
print(values, counts) # [1 2 3 4] [1 2 3 1]
Statistical Functions
import numpy as np
data = np.array([12, 45, 7, 23, 56, 9])
print(np.median(data)) # median value
print(np.percentile(data, 90)) # 90th percentile
print(np.var(data)) # variance
np.where() is one of the most versatile NumPy functions - beyond just finding indices, it can also be used to conditionally replace values, similar to an if-else applied across an entire array at once.
Coming Up Next
Next, you'll learn about Array Manipulation - reshaping, joining, and splitting NumPy arrays.