Python NumPy Cheat Sheet: Arrays, Indexing, and Tips

If you work with numbers in Python, you will meet NumPy within your first week of data work. Its ndarray type stores homogeneous data in a contiguous block of memory and lets you operate on whole arrays at once, which is why nearly every scientific stack in Python — from pandas to scikit-learn to image toolkits — is built on top of it. The catch: NumPy's surface area is large, and the details that matter at 2 a.m. (does this slice return a view? which axis does sum collapse? why did my float32 suddenly become float64?) are easy to forget.

This Python NumPy cheat sheet collects the syntax you actually use day to day — creation, indexing, math, reshaping, linear algebra, random numbers, and file I/O — plus the practical gotchas that bite in real code. It targets the current stable line, NumPy 2.5, so the APIs below match what you will see in a fresh install today.

Table of Contents#

  1. Why NumPy Instead of Python Lists
  2. Quick Start: Install, Import, and the ndarray
  3. Array Creation Cheatsheet
  4. dtypes and Type Casting
  5. Indexing, Slicing, and Selection
  6. Views vs. Copies: The Silent Bug
  7. Reshaping and Combining Arrays
  8. Broadcasting Rules Made Simple
  9. Math, ufuncs, and Aggregations
  10. Working with NaN and Missing Values
  11. Sorting, Searching, and Set Operations
  12. Linear Algebra Essentials
  13. Random Numbers the Modern Way
  14. Saving and Loading Arrays
  15. Practical Recipes for Real Work
  16. Best Practices and Common Pitfalls
  17. NumPy 2.x Changes Worth Knowing
  18. Conclusion
  19. References

Why NumPy Instead of Python Lists#

Python lists are flexible containers of arbitrary Python objects. NumPy arrays are fixed-type buffers. That single design difference produces the wins people reach for NumPy to get:

ConcernPython listNumPy ndarray
Element typesMixed per elementOne dtype per array
MemoryPointers to objectsOne contiguous buffer
Math on many elementsExplicit Python loopVectorized C-level loop
Broadcast a scalar across 1M itemsLoop or list comprehensionOne expression
Typical useGeneral scriptingNumerical work at scale

Two rules follow from the design and explain most beginner confusion:

  1. Every element shares one data type (dtype).
  2. The total size is fixed at creation — you do not append to grow an array the way you would a list; you allocate a new array or preallocate and fill.

Quick Start: Install, Import, and the ndarray#

pip install numpy
import numpy as np  # universal convention

The central object is the ndarray — an N-dimensional, rectangular grid of same-type values. A 1-D array behaves like a vector, a 2-D array like a table, and higher dimensions stack those tables; the number of dimensions is the ndim.

a = np.array([1, 2, 3, 4])
b = np.array([[1, 2, 3],
              [4, 5, 6]])
 
print(a.ndim, b.ndim)     # 1 2
print(b.shape)            # (2, 3)   -> 2 rows, 3 columns
print(b.size)             # 6        -> total element count
print(b.dtype)            # int64    (platform default integer)
print(b.nbytes)           # 48       -> 6 elements * 8 bytes

Core attributes to memorize: shape (tuple of dimension lengths), ndim (number of axes), size (element count), dtype (element type), nbytes (memory used by the buffer), T (transpose view).

Array Creation Cheatsheet#

# From Python sequences (int64/float64 inferred from the data)
np.array([1, 2, 3])
np.array([[1, 2], [3, 4]])
 
# Filled arrays
np.zeros(5)                  # [0. 0. 0. 0. 0.]
np.zeros((2, 3), dtype=np.int32)
np.ones(4)
np.full((2, 2), 7)           # every entry is 7
np.empty(3)                  # uninitialized memory (fastest, fill before reading!)
np.eye(3)                    # 3x3 identity
np.identity(3)
 
# Ranges
np.arange(0, 10, 3)          # [0 3 6 9]  — step-based, like range()
np.linspace(0, 1, 5)         # [0.  0.25 0.5  0.75 1.  ]  — 5 points incl. stop
np.logspace(0, 3, 4)         # [1.  10.  100.  1000.]  — powers of 10
 
# Reshaped / repeated
np.arange(6).reshape(2, 3)
np.tile([1, 2], 3)           # [1 2 1 2 1 2]
np.repeat([1, 2], 3)         # [1 1 1 2 2 2]
 
# Casting and copying
np.asarray([1, 2, 3])    # array if needed, no copy if possible
arr = np.array([1, 2, 3])
arr.astype(np.float32)   # convert dtype (always a copy)
arr.copy()               # explicit deep copy of the buffer

arange vs linspace: use arange(start, stop, step) when you know the step and want integer-like sequences; use linspace(start, stop, num) when you know how many points you need and want the endpoint included. arange with float steps is fragile — rounding can drop the last value — prefer linspace for floats.

dtypes and Type Casting#

arr = np.array([1, 2, 3], dtype=np.float32)
arr.dtype                  # dtype('float32')
arr.astype(np.int64)       # explicit cast
arr.astype(np.uint8)       # wrap-around warning territory — know your range

Common dtypes:

dtypeDescription
np.int8 … np.int64Signed integers (size in name)
np.uint8 … np.uint64Unsigned (e.g. image bytes 0–255)
np.float32, np.float64Single / double precision floats
np.complex64, np.complex128Complex numbers
np.bool_Booleans
np.intpInteger matching pointer width (default integer on 64-bit)

Pick the smallest dtype that safely holds your range: np.float32 halves memory versus np.float64, and np.uint8 is the natural type for 0–255 pixel data. Cast explicitly at the boundaries of your pipeline (arr.astype(...)) instead of letting NumPy infer repeatedly.

Indexing, Slicing, and Selection#

a = np.array([10, 20, 30, 40, 50])
a[0]          # 10          (0-based)
a[-1]         # 50          (negative counts from the end)
a[1:4]        # [20 30 40]  (start:stop — stop excluded)
a[::2]        # [10 30 50]  (step)
a[::-1]       # reversed
 
m = np.arange(12).reshape(3, 4)
m[1, 2]       # 6           (row 1, column 2)
m[1]          # row 1 as a 1-D array
m[:, 0]       # first column
m[0:2, 1:3]   # sub-block: rows 0-1, columns 1-2
m[..., -1]    # last column, any number of leading dims

Boolean masks#

Comparisons produce boolean arrays; use them to filter or assign:

x = np.array([3, -1, 5, -2, 8])
x[x > 0]                 # array([3, 5, 8])
x[x > 0] = 0             # zero-out positives in place
mask = (x > -2) & (x < 5)   # combine with & | ~ (not and/or/not)

Fancy indexing#

Integer arrays select arbitrary elements or rows (always returns a copy):

rows = m[[0, 2]]         # rows 0 and 2
m[[0, 1], [2, 3]]        # elements (0,2) and (1,3)
np.take(a, [0, 4])       # 1-D equivalent, faster for simple gathers

Conditional selection#

np.where(x > 0, x, 0)        # keep positives, else 0
np.select([x < 0, x > 5], [x * -1, 5], default=x)   # multi-branch
np.clip(x, 0, 5)             # bound values to [0, 5]

Views vs. Copies: The Silent Bug#

Basic slicing returns a view: a new array object sharing the original buffer. Mutating a view mutates the source. Advanced indexing (boolean or integer arrays) returns a copy.

a = np.arange(10)
s = a[2:5]        # view
s[0] = 99
print(a)          # [0 1 99 3 4 5 6 7 8 9]  — original changed!
 
c = a[[1, 2, 3]]  # copy
c[0] = -5
print(a)          # unchanged

Rules of thumb:

  • Slice-based extraction → view. If the extracted piece outlives the parent or must not alias it, call .copy().
  • Boolean or integer-array indexing → copy. Assignments like a[a > 0] = 0 still modify a (the assignment is in place).
  • reshape and ravel usually return views; flatten always copies. Use x.base is not None as a rough view check — a view's base points at its parent.

Reshaping and Combining Arrays#

a = np.arange(6)
a.reshape(2, 3)        # new shape, same data when possible
a.reshape(3, -1)       # -1 infers the missing dimension
a.ravel()              # flattened view when possible
a.flatten()            # flattened copy
a.T                    # transpose view (swap axes for 2-D)
np.transpose(a)        # same, works for N-D
np.expand_dims(a, 0)   # add axis: (6,) -> (1, 6)
np.squeeze(np.zeros((1, 3, 1)))   # remove length-1 axes -> (3,)
a.reshape(6, 1)        # column vector

Stacking and splitting:

p = np.array([1, 2, 3])
q = np.array([4, 5, 6])
 
np.concatenate([p, q])          # [1 2 3 4 5 6]
np.stack([p, q])                # shape (2, 3) — new axis
np.vstack([p, q])               # stack rows (2, 3)
np.hstack([p, q])               # stack columns (6,)
np.column_stack([p, q])         # pair into columns (3, 2)
np.split(np.arange(8), 4)       # 4 equal parts
np.hsplit(np.arange(8).reshape(2, 4), 2)   # split columns

Broadcasting Rules Made Simple#

Broadcasting lets NumPy combine arrays of different shapes without copying data. Compare shapes from the right; each pair of dimensions is compatible when the sizes are equal or one of them is 1.

a = np.ones((3, 4))
b = np.array([10, 20, 30, 40])
 
a + b            # (3,4) + (4,) -> b stretches across rows
a * 2            # scalar always broadcasts
 
col = np.array([[1], [2], [3]])
col + b          # (3,1) + (4,) -> (3,4) outer-style combination

Classic real-world case — scale each RGB channel of an image differently:

image = np.random.default_rng(0).random((256, 256, 3))
scale = np.array([0.299, 0.587, 0.114])   # per-channel weights
weighted = image * scale                  # (256,256,3) * (3,) works

If the shapes cannot be reconciled, NumPy raises ValueError: operands could not be broadcast together. When that happens, print both .shape tuples and look for a dimension that needs reshape, expand_dims, or T. Note that the result takes the largest shape along each axis — a (5,1) plus a (1,6) pair produces (5,6), which can quietly create a large temporary.

Math, ufuncs, and Aggregations#

Arithmetic is element-wise; operators (+ - * / // % **) work between arrays and scalars and between broadcast-compatible arrays. There is no matrix multiplication in * — use @ for that.

x = np.array([1.0, 4.0, 9.0])
x + 10            # element-wise
x * x
x ** 0.5          # [1. 2. 3.]
1 / (x + 1)       # unary broadcasting

Universal functions (ufuncs) are the fast element-wise routines:

np.abs(x);  np.sqrt(x);  np.exp(x);  np.log(x)
np.sin(x);  np.cos(x);  np.round(x, 2);  np.floor(x);  np.ceil(x)
np.maximum(x, 2)          # element-wise clamp-style max
np.power(x, 2)

Aggregations reduce an array to a scalar (or to fewer dimensions):

a = np.arange(1, 7).reshape(2, 3)   # [[1 2 3], [4 5 6]]
 
np.sum(a)                 # 21
np.sum(a, axis=0)         # [5 7 9]   — collapse rows (down columns)
np.sum(a, axis=1)         # [6 15]    — collapse columns (per row)
np.mean(a, axis=1, keepdims=True)   # shape (2,1), keeps broadcasting room
np.min(a); np.max(a)
np.argmin(a); np.argmax(a)          # flat index of extreme
np.median(a); np.percentile(a, 90); np.quantile(a, 0.9)
np.std(a); np.var(a)
np.cumsum(a); np.cumprod(a)
np.any(a > 5); np.all(a > 0)
np.prod(a); np.ptp(a)               # product; max - min

axis intuition: axis=0 runs down the rows (collapses the first dimension); axis=1 runs across columns. keepdims=True leaves a length-1 axis behind so the result still broadcasts against the input — essential for per-row or per-column normalization.

Working with NaN and Missing Values#

Floating-point arrays represent missing data with np.nan. Standard aggregations propagate NaN; the nan* family ignores it.

v = np.array([1.0, np.nan, 3.0, np.nan])
 
np.isnan(v)                  # [False  True False  True]
np.mean(v)                   # nan
np.nanmean(v)                # 2.0
np.nanstd(v); np.nanvar(v); np.nanmedian(v); np.nanpercentile(v, 90)
v[~np.isnan(v)]              # drop NaNs by mask
np.nan_to_num(v, nan=0.0)    # replace NaN with 0 (or pass posinf/neginf)
np.where(np.isnan(v), 0.0, v)

Integers cannot hold NaN — cast to float first if missing values are expected.

Sorting, Searching, and Set Operations#

arr = np.array([3, 1, 4, 1, 5, 9, 2])
 
np.sort(arr)                     # ascending copy
np.sort(arr, descending=True)    # descending copy (added in NumPy 2.5)
arr.sort()                       # in-place
np.argsort(arr)                  # indices that would sort arr
np.argsort(arr)[-3:]             # indices of the three largest
np.sort(arr, kind="stable")      # stable sort (timsort/radix under the hood)
 
np.partition(arr, 3)             # 3 smallest first (partial sort, O(n))
np.searchsorted(np.sort(arr), 4) # insertion point in a sorted array
 
np.unique(arr)                   # sorted distinct values
np.unique(arr, return_counts=True)
np.flip(arr)                     # reversed copy

np.sort returns a sorted copy; ndarray.sort sorts in place. argsort is the key to "top N" queries and to reordering parallel arrays (data[idx]).

Linear Algebra Essentials#

The numpy.linalg module wraps BLAS/LAPACK. Prefer @ (or np.matmul) for matrix products — the older np.matrix class is discouraged even for linear algebra work.

A = np.array([[3.0, 1.0], [1.0, 2.0]])
b = np.array([9.0, 8.0])
 
x = np.linalg.solve(A, b)   # solve A x = b (prefer this over inv(A) @ b)
A @ x                       # matrix product
np.matmul(A, A)
np.dot(b, b)                # dot product (1-D); @ is clearer for 2-D
 
np.linalg.inv(A)            # inverse (use solve() for systems)
np.linalg.det(A)            # determinant
np.linalg.norm(b)           # vector/matrix norm
np.linalg.eig(A)            # eigenvalues, eigenvectors
np.linalg.eigh(A)           # Hermitian/symmetric — faster, more stable
np.linalg.svd(A)            # singular value decomposition
np.linalg.qr(A)             # QR factorization
np.linalg.cholesky(A)       # Cholesky (positive-definite matrices)
np.linalg.matrix_rank(A)
np.trace(A)                 # sum of diagonal

For stacked batches of matrices, many of these functions broadcast over the leading axes (for example, solving many small systems in one call). Beyond NumPy — LU, Schur, pseudoinverse variants, matrix exponentials — reach for scipy.linalg, which is less flexible with broadcasting but richer in algorithms.

Random Numbers the Modern Way#

Use the Generator API. np.random.default_rng() is the recommended constructor; avoid seeding the legacy global np.random state in library code.

rng = np.random.default_rng(42)     # reproducible; PCG64 bit generator by default
 
rng.random((2, 3))                  # uniform floats in [0, 1)
rng.integers(0, 10, size=5)         # ints in [0, 10)
rng.normal(loc=0, scale=1, size=3)  # standard normal
rng.uniform(1.0, 5.0, size=4)
rng.choice([10, 20, 30], size=2, replace=False)
rng.permutation(10)                 # shuffled copy
x = np.arange(5); rng.shuffle(x)    # in-place shuffle
rng.standard_normal(3)

Creating a generator with a fixed seed gives reproducible sequences; pass an integer, a SeedSequence, or a bit generator such as np.random.PCG64(42). Keep one rng per simulation and pass it around, rather than reseeding constantly.

Saving and Loading Arrays#

arr = np.arange(12).reshape(3, 4)
 
# Binary NumPy formats (preserve dtype and shape exactly)
np.save("data.npy", arr)
arr2 = np.load("data.npy")
 
np.savez("bundle.npz", x=arr, y=arr * 2)          # uncompressed archive
np.savez_compressed("bundle.npz", x=arr, y=arr * 2)
loaded = np.load("bundle.npz")
loaded["x"]
 
# Text formats (human-readable / interop)
np.savetxt("data.csv", arr, delimiter=",", fmt="%d")
arr3 = np.loadtxt("data.csv", delimiter=",", dtype=float)

Prefer .npy/.npz for internal pipelines — they are fast and lossless. Only pass allow_pickle=True to np.load for files you trust, since pickled payloads can execute code on load.

Practical Recipes for Real Work#

Z-score standardization (per column)#

X = np.array([[1.0, 100.0], [2.0, 200.0], [3.0, 300.0]])
Z = (X - X.mean(axis=0)) / X.std(axis=0)   # column stats broadcast over every row

Min-max scaling to [0, 1]#

lo, hi = X.min(axis=0), X.max(axis=0)
scaled = (X - lo) / (hi - lo)

One-hot encode class labels#

labels = np.array([0, 2, 1, 2])
one_hot = np.eye(3)[labels]      # shape (4, 3)

Fill missing values and clip outliers#

x = np.array([1.0, np.nan, 50.0, 3.0])
 
# Replace NaN with the mean of the observed entries, then bound the range
filled = np.where(np.isnan(x), np.nanmean(x), x)
clean = np.clip(filled, 0, 10)

Moving average (window of 3)#

s = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
window = 3
ma = np.convolve(s, np.ones(window) / window, mode="valid")  # [2. 3. 4.]

Counting and grouping#

labels = np.array([0, 2, 1, 2, 2])
counts = np.bincount(labels)                       # [1 1 3] — occurrences per class
values, freqs = np.unique(labels, return_counts=True)

Vectorized simulation instead of a loop#

rng = np.random.default_rng(0)
draws = rng.normal(size=100_000)
print(draws.mean(), draws.std())   # one pass, no Python loop

Best Practices and Common Pitfalls#

  1. Vectorize before you optimize. Replacing Python loops with array expressions is usually an order of magnitude faster or more. Reach for numba, Cython, or C only after vectorization is exhausted.
  2. Mind your dtype. Smaller types cut memory bandwidth; use np.float32 or np.uint8 where range allows, and cast with astype at well-defined boundaries.
  3. Know view vs. copy. Slice → view; boolean/fancy index → copy. Call .copy() when you mean one, and use asarray when you want "convert only if needed."
  4. Preallocate output buffers. Growing an array in a loop (via np.concatenate each iteration) is quadratic; allocate out = np.empty(n) and fill it, or use out= parameters on ufuncs to avoid temporaries.
  5. Respect memory layout. NumPy arrays are C-ordered by default (last index changes fastest). Iterate along the last axis; use np.ascontiguousarray after transposes if a kernel needs flat buffers. arr.flags["C_CONTIGUOUS"] tells you the layout.
  6. Use axis and keepdims deliberately. Broadcasting bugs almost always trace back to a missing or extra axis — keepdims=True during reductions is the usual fix.
  7. Let linalg do the linear algebra. For Ax = b, np.linalg.solve beats np.linalg.inv(A) @ b in both speed and numerical stability.
  8. Seed generators, not globals. default_rng(seed) for reproducible code; never rely on np.random.seed in anything reusable.
  9. Check shapes first. When an operation raises a broadcast or indexing error, print the shapes before anything else.
  10. Don't mix integer overflow and unsigned wrap-around silently. np.uint8(200) + np.uint8(100) wraps; accumulate in a wider dtype (arr.sum(dtype=np.int64)).

NumPy 2.x Changes Worth Knowing#

If you are upgrading old code or reading older tutorials, these differences matter (current stable line is NumPy 2.5):

  • Removed dtype aliases. np.float_ is gone — use np.float64. The long-deprecated np.int, np.float, np.bool aliases were removed earlier; use the builtin int, float, bool or explicit NumPy types.
  • Simpler promotion (NEP 50). Weak Python scalars no longer upcast arrays: np.array([1], dtype=np.float32) + 3.0 stays float32, while np.array([1], dtype=np.float32) + np.float64(3.0) becomes float64. Cast explicitly when precision matters.
  • copy= keyword semantics. np.array(obj, copy=False) now raises if a copy is unavoidable. The old "copy only if necessary" behavior is np.asarray(obj) (or copy=None).
  • Default integer is np.intp. On 64-bit systems this is 64-bit everywhere, including Windows (previously C long, 32-bit there).
  • Sorting grew descending=. np.sort(a, descending=True) arrived in NumPy 2.5 — no more [::-1] dance for reverse sorts.
  • Migration tooling. The Ruff rule NPY201 flags much of the above automatically: ruff check . --select NPY201.
  • Platform support. NumPy 2.5 targets Python 3.12–3.14 and has dropped Python 3.11 and distutils support.

Conclusion#

This Python NumPy cheat sheet covered the working vocabulary of modern NumPy: creating arrays and choosing dtypes, indexing with slices and masks, remembering that slices share memory, reshaping and stacking, broadcasting shapes together, reducing with axis/keepdims, handling NaN, sorting with the new descending option, solving linear systems, drawing reproducible random numbers, and moving arrays to disk. Layered on top are the habits that keep numerical code fast and correct — vectorize, control dtype, preallocate, and treat shapes as the first debugging step.

Keep the tables near your editor, then deepen the parts you use most (broadcasting, views, and axis semantics repay study). With NumPy 2.5 under your fingers, you are working with the same APIs the current scientific Python ecosystem expects.

References#