NumPy Cheatsheet
Aggregations
Use this NumPy reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Overview
Aggregation functions reduce one or more axes to a scalar or lower-dimensional array. Most accept axis, keepdims, where, and out arguments.
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) a.sum() # 21 — all elements a.sum(axis=0) # [5, 7, 9] — collapse rows, result shape (3,) a.sum(axis=1) # [6, 15] — collapse cols, result shape (2,) a.sum(axis=1, keepdims=True) # [[6],[15]] shape (2, 1) — preserves dims
Core Aggregation Methods
| Method / Function | Description |
|---|---|
a.sum() / np.sum(a) | Sum of elements |
a.prod() / np.prod(a) | Product of elements |
a.mean() / np.mean(a) | Arithmetic mean |
a.std() / np.std(a) | Standard deviation |
a.var() / np.var(a) | Variance |
a.min() / np.min(a) | Minimum value |
a.max() / np.max(a) | Maximum value |
np.median(a) | Median (no method form) |
np.percentile(a, q) | q-th percentile |
np.quantile(a, q) | q in [0, 1] (same as percentile/100) |
np.ptp(a) | Peak-to-peak (max - min) |
a.cumsum() | Cumulative sum |
a.cumprod() | Cumulative product |
np.cumsum(a) | Same, function form |
np.diff(a) | n-th discrete difference |
np.ediff1d(a) | Differences, 1-D, with prepend/append |
np.gradient(a) | Gradient (central differences) |
axis and keepdims
b = np.arange(24).reshape(2, 3, 4) b.sum(axis=0) # shape (3, 4) — sums over first axis b.sum(axis=(0, 2)) # shape (3,) — sums over axes 0 and 2 b.sum(axis=-1) # shape (2, 3) — sums over last axis b.mean(axis=1, keepdims=True) # shape (2, 1, 4) — keeps all axes
ddof in std / var
a = np.array([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]) a.std() # population std (ddof=0 default) → 2.0 a.std(ddof=1) # sample std (Bessel's correction) → 2.138 a.var(ddof=1) # sample variance
Min / Max with Indices
a = np.array([3, 1, 4, 1, 5, 9, 2, 6]) a.min() # 1 a.max() # 9 a.argmin() # 1 (flat index) a.argmax() # 5 b = np.array([[3, 1], [4, 2]]) b.argmin(axis=0) # [0, 0] — per-column min index b.argmax(axis=1) # [0, 0] — per-row max index
Percentile and Quantile
a = np.arange(10, dtype=float) np.percentile(a, 50) # 4.5 — median np.percentile(a, [25, 50, 75]) # [2.25, 4.5, 6.75] np.percentile(a, 90, method="linear") # default interpolation np.percentile(a, 90, method="nearest") # snap to actual value # Available methods (NumPy ≥ 1.22, replaces interpolation=) # "inverted_cdf", "averaged_inverted_cdf", "closest_observation", # "interpolated_inverted_cdf", "hazen", "weibull", "linear", # "median_unbiased", "normal_unbiased", "nearest", "midpoint", "lower", "higher" np.quantile(a, 0.5) # same but q in [0, 1] np.quantile(a, [0.25, 0.75]) # IQR bounds b = np.random.rand(4, 10) np.percentile(b, 75, axis=1) # per-row 75th percentile np.percentile(b, 75, axis=1, keepdims=True) # shape (4, 1)
Cumulative Operations
a = np.array([1, 2, 3, 4]) np.cumsum(a) # [1, 3, 6, 10] np.cumprod(a) # [1, 2, 6, 24] b = np.array([[1, 2], [3, 4]]) np.cumsum(b, axis=0) # [[1,2],[4,6]] — cumulative down rows np.cumsum(b, axis=1) # [[1,3],[3,7]] — cumulative across cols
Differences
a = np.array([1, 4, 9, 16, 25]) np.diff(a) # [3, 5, 7, 9] — first differences np.diff(a, n=2) # [2, 2, 2] — second differences np.diff(a, prepend=0) # [1, 3, 5, 7, 9] — prepend before diff np.ediff1d(a, to_begin=[-99], to_end=[99]) # prepend/append to result np.gradient(a) # [3., 4., 6., 8., 9.] — gradient (edge: one-sided) np.gradient(np.random.rand(4, 4), axis=0) # gradient along axis 0
NaN-aware Aggregations
All standard aggregations propagate NaN by default. Use nan* variants to ignore them:
| Normal | NaN-ignoring |
|---|---|
np.sum(a) | np.nansum(a) |
np.mean(a) | np.nanmean(a) |
np.std(a) | np.nanstd(a) |
np.var(a) | np.nanvar(a) |
np.min(a) | np.nanmin(a) |
np.max(a) | np.nanmax(a) |
np.argmin(a) | np.nanargmin(a) |
np.argmax(a) | np.nanargmax(a) |
np.percentile(a, q) | np.nanpercentile(a, q) |
np.quantile(a, q) | np.nanquantile(a, q) |
np.median(a) | np.nanmedian(a) |
np.cumsum(a) | np.nancumsum(a) |
np.cumprod(a) | np.nancumprod(a) |
np.prod(a) | np.nanprod(a) |
a = np.array([1.0, np.nan, 3.0, np.nan, 5.0]) np.mean(a) # nan np.nanmean(a) # 3.0 np.nansum(a) # 9.0
Boolean Aggregations
a = np.array([True, False, True, True]) np.any(a) # True — at least one True np.all(a) # False — not all True np.count_nonzero(a) # 3 b = np.array([[1, 0], [3, 4]]) np.any(b, axis=0) # [True, True] np.all(b, axis=1) # [False, True] np.count_nonzero(b, axis=0) # [2, 1]
where argument (conditional aggregation)
a = np.array([1.0, -2.0, 3.0, -4.0, 5.0]) mask = a > 0 np.sum(a, where=mask, initial=0) # sum only positive values → 9.0 np.mean(a, where=mask) # mean of positive values
initialis required forsum/prodwhen usingwhere, so NumPy knows the identity element for empty selections.
Weighted and Moving Aggregations
a = np.array([1.0, 2.0, 3.0, 4.0]) w = np.array([1.0, 2.0, 3.0, 4.0]) np.average(a, weights=w) # weighted average = (1+4+9+16)/10 = 3.0 np.average(a) # unweighted mean (same as np.mean) # Moving average (window=3) via convolution window = np.ones(3) / 3 np.convolve(a, window, mode="valid") # [2., 3.] np.convolve(a, window, mode="same") # [1., 2., 3., 2.333]
Histogram
data = np.random.randn(1000) counts, edges = np.histogram(data, bins=20) counts, edges = np.histogram(data, bins=20, range=(-3, 3)) counts, edges = np.histogram(data, bins=np.linspace(-3, 3, 21)) density, edges = np.histogram(data, bins=20, density=True) # normalize to PDF # 2-D histogram x = np.random.randn(1000) y = np.random.randn(1000) H, xedges, yedges = np.histogram2d(x, y, bins=10) H, xedges, yedges = np.histogram2d(x, y, bins=[20, 15]) # Histogram bin indices np.digitize(data, bins=edges) # which bin each value falls into
Unique and Set Operations
a = np.array([3, 1, 2, 1, 3, 3]) np.unique(a) # [1, 2, 3] np.unique(a, return_counts=True) # ([1,2,3], [2,1,3]) np.unique(a, return_index=True) # (unique, first-occurrence indices) np.unique(a, return_inverse=True) # (unique, indices to reconstruct a) np.bincount(a) # [0, 2, 1, 3] — count of each non-neg int (0-indexed) np.bincount(a, weights=np.ones_like(a, dtype=float)) # weighted count