NumPy Cheat Sheet
NumPy arrays, operations, broadcasting, and linear algebra essentials.
2 PagesIntermediateMay 4, 2026
Creating Arrays
Construct NumPy arrays.
python
import numpy as npa = np.array([1, 2, 3])zeros = np.zeros((2, 3))ones = np.ones((3, 3))range_arr = np.arange(0, 10, 2)lin = np.linspace(0, 1, 5)
Shape & Indexing
Inspect and slice arrays.
python
a.shape # (rows, cols)a.reshape(3, 2)a[0, :] # First rowa[:, 1] # Second columna[a > 2] # Boolean indexing
Vectorized Operations
Element-wise math without loops.
python
b = a * 2c = a + bd = np.sqrt(a)sum_all = a.sum()mean_val = a.mean()
Broadcasting
Operate on arrays of different shapes.
python
m = np.array([[1, 2], [3, 4]])v = np.array([10, 20])result = m + v # v is "broadcast" across each row
Linear Algebra
Matrix products, solves, and decompositions.
python
A @ B # matrix multiplynp.dot(a, b) # dot productnp.linalg.inv(A) # inversenp.linalg.solve(A, b) # solve Ax = b (prefer over inv)np.linalg.det(A) # determinantvals, vecs = np.linalg.eig(A)U, S, Vt = np.linalg.svd(A)np.linalg.norm(v) # L2 norm
Random Sampling
Use the modern Generator API for reproducible randomness.
python
rng = np.random.default_rng(seed=42)rng.random((3, 3)) # uniform [0,1)rng.integers(0, 10, size=5) # ints in [0,10)rng.normal(loc=0, scale=1, size=100)rng.choice([1, 2, 3], size=4, replace=False)rng.shuffle(arr) # in-placerng.permutation(arr) # returns a copy
Boolean & Fancy Indexing
Select and modify elements by mask or index array.
python
a[a > 5] # boolean mask selecta[(a > 2) & (a < 8)] # combine with & | ~a[a < 0] = 0 # masked assignmentnp.where(a > 0, a, -a) # vectorized ternary -> absidx = np.array([0, 2, 4])a[idx] # fancy indexingnp.nonzero(a) # indices of nonzero elementsnp.clip(a, 0, 1) # bound values
Axis-Aware Aggregations
Reductions and their NaN-safe variants.
- a.sum(axis=0)- reduce down rows, keeping one value per column
- a.mean(axis=1, keepdims=True)- row means preserving dimensions for broadcasting
- np.nanmean / np.nansum- aggregations that ignore NaN values
- a.argmax(axis=0)- index of the max along an axis, not the value
- np.cumsum / np.cumprod- running totals along an axis
- np.percentile(a, 95)- value at a given percentile of the data
Pro Tip
Avoid Python for-loops over NumPy arrays — vectorized operations are implemented in C and are dramatically faster.
Was this cheat sheet helpful?
Explore Topics
#NumPy#NumPyCheatSheet#DataScience#Intermediate#CreatingArrays#ShapeIndexing#VectorizedOperations#Broadcasting#DataStructures#MachineLearning#CheatSheet#SkillVeris