Working with NumPy Arrays
Working with NumPy Arrays
NumPy is the foundation under almost every Python ML library. Its ndarray stores numbers in contiguous memory and runs vectorized operations without Python loops. That speed difference is what makes real datasets feasible.
Create Arrays
import numpy as np
a = np.array([1, 2, 3])
b = np.ones((2, 3))
c = np.zeros(4)
d = np.arange(0, 10, 2)
print(a, b, c, d)Vectorized Math
Operations apply element by element without explicit loops:
x = np.array([1, 2, 3, 4])
y = x * 2
z = x + y
print(x.mean())
print(x.sum())
print(x ** 2)Why does this matter? A loop over a million Python floats is slow. The same operation over a NumPy array runs in compiled C. Always prefer vectorized expressions such as x * 2 over manual iteration.
Shapes and Reshaping
Understand shape, size, and dtype. Shape mismatches are the most common NumPy error, and a read of the shape usually shows the fix.
m = np.arange(12).reshape(3, 4)
print(m.shape)
print(m[1, 2])
print(m.sum(axis=0))axis=0 collapses rows; axis=1 collapses columns. Practice on a small matrix until the two feel natural.
Indexing and Slicing
NumPy indexing uses the same brackets as lists but supports fancy indexing with arrays of positions and boolean masks, which you will use constantly for filtering data.
Key Points
- NumPy arrays enable fast, vectorized math.
- Use operators like
*and+instead of loops. - Check
shapefirst when an operation fails. - Slicing and masking make filtering data easy.