Menu
CoddyTech

NumPy Cheat Sheet

Last updated

Create arrays

An array holds values of one type in a grid of any number of dimensions.

TaskCode
Import NumPyimport numpy as np
From a listnp.array([1, 2, 3])
2D from nested listsnp.array([[1, 2, 3], [4, 5, 6]])
Zeros, ones, one fill valuenp.zeros((2, 3)), np.ones(4), np.full((2, 2), 7)
Range with a step (end excluded)np.arange(0, 10, 2) # [0 2 4 6 8]
n evenly spaced points (end included)np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.]
Identity matrixnp.eye(3)
Same shape as another arraynp.zeros_like(m), np.ones_like(m)
Choose the element typenp.array([1, 2, 3], dtype=np.float32)
Coordinate gridsxx, yy = np.meshgrid(np.arange(3), np.arange(2))

Inspect an array

TaskCode
Shape: size of each dimensionm.shape # (3, 4)
Number of dimensionsm.ndim # 2
Number of elementsm.size # 12
Element typem.dtype # int64
Convert the typem.astype(np.float64)
Length of the first dimensionlen(m) # 3
Back to a Python listm.tolist()
Print fewer decimalsnp.set_printoptions(precision=3, suppress=True)

Index and slice

Slices are views: they share memory with the original array. Masks and index lists return copies.

TaskCode
First and last elementa[0], a[-1]
Slice start:stop (stop excluded)a[1:4] # [20 30 40]
Every second element, reverseda[::2], a[::-1]
One element of a 2D arraym[1, 2] # 6
A row, a columnm[0], m[:, 1]
A block of rows and columnsm[:2, 1:3]
Elements that match a conditiona[a > 25] # [30 40 50]
Combine conditionsa[(a > 15) & (a < 45)]
Pick by a list of positionsa[[0, 2, 4]]
Positions that matchnp.flatnonzero(a > 25) # [2 3 4]
Choose per elementnp.where(a > 25, a, 0)
Copy before changing a slicepart = a[1:3].copy()
Set values with a maska[a > 40] = 0

Math and broadcasting

Operators work element by element. Broadcasting stretches a scalar, row or column to match the other array's shape.

TaskCode
Element-wise arithmeticx + y, x - y, x * y, x / y, x ** 2
With a scalarx * 10
Square root, exponent, lognp.sqrt(x), np.exp(x), np.log(x)
Absolute value, roundingnp.abs(x - 5), np.round(x / 3, 2)
Limit values to a rangenp.clip(x, 2, 8)
Element-wise maximumnp.maximum(x, 3)
Dot productx @ y # 37.0
Center each column (broadcast a row)m - m.mean(axis=0)
Scale each row (broadcast a column)m / m.sum(axis=1, keepdims=True)
Compare floats safelynp.isclose(0.1 + 0.2, 0.3) # True, np.allclose(x, y)
Trigonometry and pinp.sin(np.pi / 2) # 1.0

Aggregate along an axis

axis=0 works down the rows and gives one result per column. axis=1 works across the columns and gives one result per row.

TaskCode
Total of all elementsm.sum() # 21
One result per columnm.sum(axis=0) # [5 7 9]
One result per rowm.sum(axis=1) # [ 6 15]
Mean and standard deviationm.mean(), m.std(), m.mean(axis=0)
Minimum, maximumm.min(), m.max(axis=1)
Position of the maximumm.argmax(), m.argmax(axis=1)
Median and percentilesnp.median(m), np.percentile(m, [25, 50, 75])
Running totalnp.cumsum(m, axis=1)
Product of all elementsm.prod() # 720
Any, all, count(m > 4).any(), (m > 0).all(), np.count_nonzero(m > 2)

Reshape and combine

A reshape keeps the elements and changes the shape, so the total size must stay the same.

TaskCode
New shapea.reshape(2, 3)
Let NumPy work out one sizea.reshape(3, -1), a.reshape(-1, 1)
Flatten to 1Dm.ravel(), m.flatten()
Transposem.T
Add a dimensiona[:, np.newaxis], np.expand_dims(a, axis=0)
Drop dimensions of size 1np.squeeze(np.ones((1, 3, 1)))
Join along an existing axisnp.concatenate([a, a])
Stack rows or columnsnp.vstack([m, m]), np.hstack([m, m])
1D arrays as columnsnp.column_stack([a, a ** 2])
Stack along a new axisnp.stack([a, a], axis=0) # shape (2, 6)
Split into piecesnp.split(a, 3), np.array_split(a, 4)
Repeat or tilenp.repeat([1, 2], 2) # [1 1 2 2], np.tile([1, 2], 2) # [1 2 1 2]

Sort, search and unique values

TaskCode
Sorted copynp.sort(a)
Largest firstnp.sort(a)[::-1]
Positions that would sortnp.argsort(a)
Three largest valuesnp.sort(a)[-3:]
Unique values and their countsvalues, counts = np.unique(a, return_counts=True)
NumPy 2 names (unique_values may be unsorted)np.unique_values(a), np.unique_counts(a)
Is each element in a list?np.isin(a, [1, 9])
Insert position in a sorted arraynp.searchsorted([1, 3, 5, 7], 4) # 2
Set operationsnp.intersect1d(a, [1, 2, 10]), np.union1d(a, [10]), np.setdiff1d(a, [1])
Sort rows by one columnm[m[:, 1].argsort()]

Random numbers

Create one seeded Generator and draw everything from it, so results repeat run after run.

TaskCode
Seeded generatorrng = np.random.default_rng(42)
Floats in [0, 1)rng.random(3)
Integers, high end excludedrng.integers(1, 7, size=10)
Normal distributionrng.normal(loc=0, scale=1, size=(2, 3))
Uniform floats in a rangerng.uniform(5, 10, size=4)
Pick from a listrng.choice(["a", "b", "c"], size=5)
Pick without repeatsrng.choice(10, size=3, replace=False)
Pick with weightsrng.choice(["H", "T"], size=10, p=[0.7, 0.3])
Shuffled copy, shuffle in placerng.permutation(a), rng.shuffle(a)
Binomial and Poisson countsrng.binomial(10, 0.5, size=5), rng.poisson(3, size=5)

Linear algebra

TaskCode
Matrix productA @ A
Solve Ax = bnp.linalg.solve(A, b) # [0.8 1.4]
Inverse and determinantnp.linalg.inv(A), np.linalg.det(A)
Vector lengthnp.linalg.norm(b)
Eigenvalues and eigenvectorsvalues, vectors = np.linalg.eig(A)
Fit a straight lineslope, intercept = np.polyfit(x, y, 1)
Outer productnp.outer([1, 2], [3, 4])
Diagonal and tracenp.diag(A), np.trace(A)

Missing and special values

np.nan marks a missing float. Any arithmetic with it gives nan, so use the nan functions or a mask.

TaskCode
Missing valuenp.nan
Find missing valuesnp.isnan(v), np.isnan(v).sum()
Drop missing valuesv[~np.isnan(v)]
Replace missing and infinite valuesnp.nan_to_num(v, nan=0.0, posinf=0.0)
Infinity and finite checksnp.inf, np.isfinite(v)
Statistics that skip NaNnp.nanmean(v[:3]) # 2.0, np.nanmax(v)

Save and load

TaskCode
One array, binary filenp.save("data.npy", m), m = np.load("data.npy")
Several arrays in one filenp.savez("data.npz", x=x, y=y), np.load("data.npz")["x"]
Write CSV textnp.savetxt("data.csv", m, delimiter=",", fmt="%d")
Read CSV textnp.loadtxt("data.csv", delimiter=",")

NumPy 2: old names and what to write now

NumPy 2 removed many aliases, so code copied from older tutorials can fail with an AttributeError.

TaskNumPy 2Old form
Missing valuenp.nannp.NaN
Infinitynp.infnp.Inf
64-bit float typenp.float64np.float_
Area under a curvenp.trapezoid(y, x)np.trapz(y, x)
Is each element in another array?np.isin(a, b)np.in1d(a, b)
Stack rowsnp.vstack([a, a])np.row_stack([a, a])
Productnp.prod(a)np.product(a)
Random numbersrng = np.random.default_rng(0) rng.random(3)np.random.seed(0) np.random.rand(3)

The NumPy calls that data science code is built on, grouped by task: create arrays, inspect them, index and slice, do element-wise math, aggregate along an axis, reshape and combine, sort and search, draw random numbers, and solve linear algebra. Each row is a short snippet you can paste, plus one line on what it does.

Everything here is written for NumPy 2, the version Coddy runs, and the last table lists the names NumPy 2 removed, next to what to write instead. Most examples use a = np.array([3, 1, 4, 1, 5, 9, 2, 6]) and m = np.arange(12).reshape(3, 4). New to Python itself? Start with the Python cheat sheet and the Python playground, and keep the pandas, Matplotlib and scikit-learn cheat sheets next to this one.

NumPy cheat sheet FAQ

Is this NumPy cheat sheet free?
Yes. This NumPy cheat sheet is completely free, with no sign-up required. Bookmark it, or print it to PDF from your browser, and come back whenever you need the exact call for a reshape, an axis sum or a random draw.
Which NumPy version does this cheat sheet cover?
NumPy 2. Every snippet runs on NumPy 2.4, the version Coddy runs. NumPy 2 removed aliases such as np.NaN, np.float_, np.trapz and np.in1d, so the last table shows each one next to its current name.
What does axis=0 mean in NumPy?
The axis is the dimension that gets collapsed. In a 2D array, axis=0 runs down the rows, so m.sum(axis=0) returns one total per column. axis=1 runs across the columns and returns one total per row. With no axis, the function uses every element.
What is the difference between a view and a copy?
A slice such as a[1:3] is a view: it shares memory with a, so changing the slice changes a. Boolean masks and index lists such as a[a > 2] or a[[0, 2]] return copies. Call .copy() when you need an independent array.
Why use a NumPy array instead of a Python list?
Arrays store one type in one block of memory, so math on a whole array runs in compiled code and is often many times faster than a Python loop. a * 2 doubles every element, while [1, 2] * 2 repeats the list. pandas and scikit-learn are built on NumPy arrays.
Should I use np.random.seed or default_rng?
Use rng = np.random.default_rng(seed) and call methods on rng, such as rng.normal() or rng.integers(). It is the recommended API, with better random streams and no hidden global state. np.random.seed and np.random.rand still work but are the legacy interface.
Can I run NumPy code online?
Yes. The free Matplotlib playground runs Python with NumPy, pandas, Matplotlib and scikit-learn in your browser, so you can paste any snippet from this cheat sheet and run it without installing anything. Coddy's Machine Learning course teaches NumPy step by step as part of working with real data.
Coddy programming languages illustration

Learn NumPy with Coddy

GET STARTED