Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 49 ยท Practice and Review

NumPy Cheat Sheet

A one-page NumPy 2 cheat sheet with tables for creating arrays, indexing, math, reshaping, linear algebra, random numbers and file I/O, plus runnable examples.

You have now met most of NumPy. This page is the quick-reference version: tables you can scan in seconds, a few runnable examples for each area, and links back to the lesson that explains the details. Use it when you remember that a function exists but not its exact name or argument order.

All tables assume import numpy as np and arrays named a and b. Everything here targets NumPy 2.x. Examples that print random numbers use a seeded generator, so the output is always the same.

flowchart LR
  C["Create<br/>array, zeros, arange"] --> I["Select<br/>index, slice, mask"]
  I --> M["Compute<br/>ufuncs, axis, broadcasting"]
  M --> S["Reshape and combine<br/>reshape, stack, sort"]
  S --> O["Save or analyze<br/>linalg, save, plot"]

The usual life of an array: build it, select from it, compute, rearrange, then store or analyze it.

Creating arrays

Goal Code Result
From a list np.array([1, 2, 3]) [1 2 3]
Zeros / ones np.zeros((2, 3)), np.ones(4) floats, filled with 0 or 1
Same value np.full((2, 2), 7) [[7 7] [7 7]]
Uninitialized np.empty(3) garbage values; fill before use
Integer range np.arange(0, 10, 3) [0 3 6 9] (stop excluded)
Even spacing np.linspace(0, 1, 5) 5 points, both ends included
Log spacing np.logspace(0, 3, 4) [1 10 100 1000]
Identity np.eye(3), np.identity(3) 3 by 3 identity matrix
Diagonal np.diag([1, 2, 3]) matrix with the values on the diagonal
Same shape as a np.zeros_like(a) zeros with a's shape and dtype
Grid of coordinates np.meshgrid(x, y) two 2D arrays
From a function np.fromfunction(f, (3, 3)) f applied to index grids
Repeat np.tile(a, 2), np.repeat(a, 2) whole array or each element

Attributes you will check constantly: a.shape, a.ndim, a.size, a.dtype, a.itemsize, a.nbytes. Convert types with a.astype(np.float32). See Creating Arrays and Data Types.

Python Creation functions in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Indexing and selection

Goal Code Notes
One element a[1, 2] or a[-1, -1] one comma-separated index per axis
Row / column a[0], a[:, 1] a slice keeps the axis you leave open
Slice with step a[::2, ::2] start:stop:step per axis
Reverse a[::-1] a view, no copy
Many axes at once a[..., 0] ... stands for all remaining axes
Add an axis a[:, np.newaxis] (n,) becomes (n, 1)
Boolean mask a[a > 3] always a 1D copy of matches
Combine masks (a > 1) & (a < 5), ~mask use & | ~, with parentheses
Choose by condition np.where(a > 3, x, y) three-argument form
Positions of True np.nonzero(mask), np.argwhere(mask) indexes instead of values
Fancy indexing a[[0, 2], [1, 3]] picks pairs (0,1) and (2,3); copy
Clamp values np.clip(a, lo, hi) limits both ends

The key rule: basic slices are views, masks and index lists are copies. Check with np.shares_memory(a, b) or b.base. Details: Indexing and Slicing, Boolean Masks, Fancy Indexing, Views vs Copies.

Python Selecting and the view trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Math and aggregation

Operators work element by element: a + b, a * b, a ** 2, a % 3. Mismatched shapes are broadcast if each trailing dimension is equal or 1 (see Broadcasting).

Goal Code
Elementwise functions np.sqrt, np.exp, np.log, np.abs, np.sign, np.sin
Rounding np.round(a, 2), np.floor, np.ceil, np.trunc
Totals a.sum(), a.prod(), a.cumsum(), a.cumprod()
Averages a.mean(), np.median(a), a.std(), a.var()
Extremes a.min(), a.max(), a.argmin(), a.argmax()
Percentiles np.percentile(a, 90), np.quantile(a, 0.9)
Along an axis a.sum(axis=0) (down the rows), a.sum(axis=1) (across the columns)
Keep dimensions a.mean(axis=0, keepdims=True)
Ignore NaN np.nansum, np.nanmean, np.nanmax
Compare arrays np.array_equal(a, b), np.allclose(a, b), np.isclose(a, b)
Test for NaN / inf np.isnan(a), np.isfinite(a)
Logic np.logical_and, np.logical_or, a.any(), a.all()

Remember axis names the axis that disappears: sum(axis=0) on a (3, 4) array gives shape (4,). Never compare floats with ==; use np.isclose or np.allclose. More in Vectorized Operations, Aggregations and Axes and Comparing Arrays and Floating Point.

Python Axes, broadcasting and NaN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Shape, joining and sorting

Goal Code Notes
Change shape a.reshape(2, 3), a.reshape(-1, 2) -1 means "work it out"; usually a view
Flatten a.ravel() / a.flatten() ravel may return a view, flatten always copies
Transpose a.T, np.swapaxes(a, 0, 1) a view
Add / remove axis np.expand_dims(a, 0), np.squeeze(a) length-1 axes only
Join along an axis np.concatenate([a, b], axis=0) other axes must match
Join along a new axis np.stack([a, b]) inputs must have equal shape
Shortcuts np.vstack, np.hstack, np.column_stack
Split np.split(a, 3), np.array_split(a, 4) array_split allows uneven parts
Sort values np.sort(a), a.sort() the method sorts in place
Sort order np.argsort(a) indexes that would sort a
Descending np.sort(a)[::-1] reverse the sorted view
Find insert spot np.searchsorted(sorted_a, v) needs sorted input
Unique values np.unique(a, return_counts=True) sorted values plus counts
Membership np.isin(a, [1, 2]) boolean mask
Histogram np.bincount(a), np.histogram(a, bins=5)

See Reshaping Arrays, Joining and Splitting, Sorting and Searching and Unique Values, Sets and Counting.

Python Reshape, join, sort and count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Linear algebra

Goal Code
Matrix product A @ B (same as np.matmul(A, B))
Dot product np.dot(u, v)
Outer product np.outer(u, v)
Cross product np.cross(u, v) (3D vectors)
Transpose / trace A.T, np.trace(A)
Determinant np.linalg.det(A)
Inverse np.linalg.inv(A)
Solve Ax = b np.linalg.solve(A, b)
Least squares np.linalg.lstsq(A, b)
Norm np.linalg.norm(v)
Eigenvalues np.linalg.eig(A), or np.linalg.eigh(A) if symmetric
Decompositions np.linalg.svd, np.linalg.qr, np.linalg.cholesky
Rank / condition np.linalg.matrix_rank(A), np.linalg.cond(A)
Sum over named axes np.einsum("ij,jk->ik", A, B)

* multiplies element by element; @ is the matrix product. To solve a system, call solve rather than multiplying by inv(A): it is faster and numerically safer. See Vectors and Dot Products, Matrix Operations, Solving Linear Systems, Eigenvalues and SVD and einsum.

Python Matrix product, inverse and solve

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Random numbers

Create one generator and call its methods. The old np.random.seed() and np.random.rand() still work but share hidden global state; new code should use default_rng.

Goal Code
Make a generator rng = np.random.default_rng(42)
Floats in [0, 1) rng.random(5)
Integers rng.integers(low, high, size=5) (high excluded)
Uniform range rng.uniform(2, 5, size=5)
Normal rng.normal(loc, scale, size=5)
Other distributions rng.binomial, rng.poisson, rng.exponential, rng.beta
Pick from a list rng.choice(items, size=3, replace=False)
Shuffle in place rng.shuffle(a)
Shuffled copy rng.permutation(a)
Independent streams rng.spawn(2)

The same seed always gives the same numbers on the same NumPy version, which makes experiments repeatable. Read Random Numbers with Generators and Probability Distributions for the details.

Python Seeded random numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Saving and loading

Goal Code
One array, binary np.save("a.npy", a) / np.load("a.npy")
Several arrays np.savez("data.npz", x=x, y=y) or np.savez_compressed(...)
Text, CSV-like np.savetxt("a.csv", a, delimiter=",") / np.loadtxt("a.csv", delimiter=",")
Text with gaps np.genfromtxt("a.csv", delimiter=",")
Raw bytes a.tobytes() / np.frombuffer(data, dtype=...)
Huge files np.load("big.npy", mmap_mode="r")

The file functions accept any file-like object, so io.BytesIO and io.StringIO work for tests and for this page's examples. .npy is fast and keeps dtype and shape; text files are portable but lose precision unless you choose a format. Loading .npy files with pickled objects needs allow_pickle=True, which you should only do for files you trust. See Saving and Loading Arrays.

Python A save and load round trip in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Habits worth keeping

  • Think in whole arrays. If you write a Python for loop over elements, look for a ufunc, a mask or an axis argument first (Writing Fast NumPy Code).
  • Check shape and dtype whenever a result looks wrong. Most bugs are a shape of (n,) where you wanted (n, 1), or an integer dtype that wrapped around (Common Pitfalls).
  • Use .copy() when you need an independent array, and know that slicing gives a view.
  • Seed a generator for anything you want to reproduce, and compare floats with np.isclose.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a.sum(axis=0) do to an array of shape (3, 4)?

    The axis you name is the one that disappears. Summing along axis 0 collapses the three rows, leaving one total per column, so the result has shape (4,).
  2. 2. Which line gives you a new array that does NOT share memory with a?

    Basic slices, transposes and most reshapes return views. Fancy indexing with a list of positions always builds a copy.
  3. 3. How should you create random numbers in new NumPy code?

    default_rng returns a Generator object that owns its state, is reproducible, and is the recommended API. The legacy global functions still work but share hidden state.
  4. 4. What is the safest way to check that 0.1 + 0.2 equals 0.3 in an array program?

    Floating-point sums carry tiny rounding errors, so exact equality can fail. isclose and allclose compare within a tolerance.

Summary

  • Create arrays with array, zeros, arange, linspace and friends; inspect them with shape, ndim, size and dtype.
  • Slices are views; masks and index lists are copies. Use &, |, ~ with parentheses for combined conditions.
  • axis names the dimension that collapses; keepdims=True keeps it so results broadcast back.
  • reshape, concatenate, stack, split, sort and unique cover most rearranging work.
  • Use @ for matrix products and solve instead of inv for linear systems.
  • Generate random data with default_rng(seed), and save arrays with np.save or np.savez_compressed.

Want more? Revisit the Practice Exercises or the Interview Questions, or jump back to What Is NumPy? to start the course again.