Every modern Python data science library — Pandas, Scikit-learn, SciPy, PyTorch, and TensorFlow — is built upon the foundational data structures of NumPy. In this class, we master high-performance array operations, boolean masking, and multi-dimensional broadcasting rules.
A NumPy ndarray consists of three components:
float64, int32, uint8).Broadcasting allows mathematical operations between arrays of different shapes without allocating redundant memory:
Array A: (4, 1, 6) → Matches: Dimension 2 is 1 (stretched to 5)
Array B: (5, 6) → Prepended with 1 → (1, 5, 6) → Dimension 0 is 1 (stretched to 4)
Output: (4, 5, 6) → Fully compatible broadcast!
import numpy as np
import time
# Create 10 million random numbers
n = 10_000_000
arr = np.random.randn(n)
# 1. Pure Python Loop (Agonizingly Slow)
t0 = time.time()
py_result = [max(x, 0) for x in arr[:100_000]] # Only test 1% to avoid waiting
print(f"Python list comprehension (100k): {time.time() - t0:.4f}s")
# 2. NumPy Vectorized Operation (Blazing Fast C Execution)
t0 = time.time()
np_result = np.maximum(arr, 0) # Executes on all 10,000,000 elements!
print(f"NumPy vectorized maximum (10M): {time.time() - t0:.4f}s (100x faster!)")
# 3. Broadcasting Example: Mean Centering a Matrix
matrix = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
col_means = matrix.mean(axis=0) # Shape (3,)
centered_matrix = matrix - col_means # Broadcasts (3,) across (3, 3)
print("\nMean Centered Matrix:\n", centered_matrix)
If you catch yourself writing a for loop over individual rows of a numeric NumPy array or Pandas DataFrame, stop immediately! A vectorized alternative or np.where() statement exists that runs 50x to 200x faster.
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
The mathematical theory powering NumPy's N-dimensional array routines.
Build upon NumPy's array foundations with labeled Series and DataFrames.
Explore next-generation vectorized computing with Apache Arrow memory.
Implement gradient descent algorithms from scratch using NumPy vectorization.