Aller au contenu principal

10.1 - NumPy Fundamentals

Theory 30 min Advanced

Why NumPy?

NumPy provides N-dimensional arrays with vectorized operations that are 10-100× faster than Python lists for numerical computing.

import numpy as np

# Python list — slow
python_list = list(range(1_000_000))
%timeit [x**2 for x in python_list] # ~200ms

# NumPy array — fast
arr = np.arange(1_000_000)
%timeit arr**2 # ~1ms (200× faster!)

Creating Arrays

import numpy as np

# From lists
a = np.array([1, 2, 3, 4, 5])
m = np.array([[1, 2, 3], [4, 5, 6]]) # 2D (matrix)

# Factory functions
np.zeros((3, 4)) # 3×4 matrix of zeros
np.ones((2, 3)) # 2×3 matrix of ones
np.full((2, 2), 7) # 2×2 matrix filled with 7
np.eye(4) # 4×4 identity matrix
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
np.random.rand(3, 3) # random 3×3 from uniform [0,1)
np.random.randn(3, 3) # random 3×3 from standard normal

Array Properties

a = np.array([[1, 2, 3], [4, 5, 6]])

a.shape # (2, 3) — rows, cols
a.ndim # 2 — number of dimensions
a.size # 6 — total elements
a.dtype # dtype('int64')
a.T # transpose: (3, 2) shape

Indexing and Slicing

a = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]

a[1, 2] # 6 (row 1, col 2)
a[0, :] # [0, 1, 2, 3] — first row
a[:, 2] # [2, 6, 10] — third column
a[1:, 1:3] # sub-matrix rows 1-2, cols 1-2

# Boolean indexing
a[a > 5] # [6, 7, 8, 9, 10, 11]
a[a % 2 == 0] # even numbers

# Fancy indexing
a[[0, 2], :] # rows 0 and 2

Vectorized Operations

a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

a + b # [11, 22, 33, 44]
a * b # [10, 40, 90, 160]
a ** 2 # [1, 4, 9, 16]
np.sqrt(a) # [1, 1.414, 1.732, 2]

# Math functions
np.sin(a)
np.log(a)
np.exp(a)

# Aggregations
np.sum(a) # 10
np.mean(a) # 2.5
np.std(a) # 1.118
np.min(a) # 1
np.max(a) # 4
np.median(a) # 2.5
np.percentile(a, 75) # 3.25

# Along axis
m = np.array([[1, 2], [3, 4]])
np.sum(m, axis=0) # [4, 6] column sums
np.sum(m, axis=1) # [3, 7] row sums

Broadcasting

Broadcasting allows operations on arrays of different shapes:

a = np.array([[1, 2, 3], [4, 5, 6]])   # shape (2, 3)
b = np.array([10, 20, 30]) # shape (3,)

a + b # adds b to each row of a
# [[11, 22, 33],
# [14, 25, 36]]

# Normalization pattern
a = np.random.randn(100, 4)
mean = a.mean(axis=0) # shape (4,)
std = a.std(axis=0) # shape (4,)
normalized = (a - mean) / std # broadcast

Key Vocabulary

TermDefinition
ndarrayN-dimensional array — NumPy's core data structure
dtypeData type of array elements (int64, float64, bool, etc.)
shapeTuple of dimensions: (rows, cols) for 2D
BroadcastingAutomatic shape expansion for element-wise operations
VectorizationApplying operations to entire arrays at once (no Python loop)
axis=0Operate along rows (column-wise result)
axis=1Operate along columns (row-wise result)
Boolean indexingSelect elements matching a condition: arr[arr > 0]

Summary

  • NumPy arrays are 10-200× faster than Python lists for numerical operations
  • Create arrays with np.array(), np.zeros(), np.arange(), np.linspace()
  • Operations are vectorized — no need for explicit loops
  • Broadcasting automatically handles different shapes in arithmetic
  • axis=0 operates along rows; axis=1 operates along columns