NumPy Cheatsheet

Creating Arrays

Use this NumPy reference while you build software engineering projects, review code, or refresh the syntax you reach for most.

From Python Sequences

import numpy as np

np.array([1, 2, 3])                        # 1-D from list
np.array((1, 2, 3))                        # 1-D from tuple
np.array([[1, 2], [3, 4]])                 # 2-D from nested lists
np.array([1, 2, 3], dtype=np.float32)     # specify dtype
np.array([1, 2, 3], ndmin=2)              # at least 2-D → shape (1, 3)
np.asarray([1, 2, 3])                      # like array() but NO copy if already ndarray
np.asarray(existing, dtype=float)          # cast without copy when possible

Gotcha: ragged lists (lists of lists with different lengths) give dtype=object. NumPy ≥ 1.24 raises a ValueError by default; pass dtype=object explicitly.

Constant-fill Arrays

FunctionDescription
np.zeros(shape)all zeros, float64 by default
np.ones(shape)all ones, float64 by default
np.full(shape, fill_value)fill with a scalar
np.empty(shape)uninitialized (fast, garbage values)
np.zeros_like(a)zeros with same shape/dtype as a
np.ones_like(a)ones with same shape/dtype
np.full_like(a, val)fill with same shape/dtype
np.empty_like(a)uninitialized with same shape/dtype
np.zeros((3, 4))                     # shape (3, 4), float64
np.ones((2, 2), dtype=np.int32)     # shape (2, 2), int32
np.full((3,), np.pi)                 # [3.14159, 3.14159, 3.14159]
np.empty((2, 3))                     # uninitialized — values unpredictable

a = np.array([[1, 2], [3, 4]])
np.zeros_like(a)                     # same shape (2, 2) and dtype, all 0
np.full_like(a, 7)                   # [[7, 7], [7, 7]]

Sequences and Ranges

np.arange(10)              # [0, 1, ..., 9]
np.arange(1, 10)           # [1, 2, ..., 9]
np.arange(0, 1, 0.1)      # [0.0, 0.1, ..., 0.9]  — stop is exclusive
np.arange(5, dtype=float)  # [0., 1., 2., 3., 4.]

np.linspace(0, 1, 5)           # [0., .25, .5, .75, 1.]  — 5 evenly spaced INCLUDING endpoints
np.linspace(0, 1, 5, endpoint=False)   # excludes 1.0
val, step = np.linspace(0, 1, 5, retstep=True)  # also returns step size

np.logspace(0, 3, 4)           # [1., 10., 100., 1000.]  — base 10 default
np.logspace(0, 3, 4, base=2)   # 2^0 … 2^3
np.geomspace(1, 1000, 4)       # geometric spacing: [1., 10., 100., 1000.]

Prefer linspace over arange for floatsarange with float step can produce off-by-one counts due to floating-point rounding.

Identity and Diagonal

np.eye(3)                    # 3×3 identity matrix (float64)
np.eye(3, k=1)               # k>0: above diagonal; k<0: below
np.eye(3, 4)                 # 3×4 matrix with 1s on main diagonal
np.identity(3)               # strictly square identity (no k)

np.diag([1, 2, 3])           # diagonal matrix from 1-D array
np.diag(a)                   # extract main diagonal from 2-D array
np.diag(a, k=1)              # extract k-th diagonal
np.diagflat([[1, 2], [3, 4]])  # flatten then make diagonal matrix

Grid Arrays

# meshgrid — 2-D coordinate grids
x = np.linspace(-1, 1, 3)
y = np.linspace(0, 2, 3)
X, Y = np.meshgrid(x, y)          # X.shape == Y.shape == (3, 3)
X, Y = np.meshgrid(x, y, indexing="ij")  # matrix (i=x, j=y) indexing

# mgrid — dense, slice-based
G = np.mgrid[0:3, 0:4]            # G.shape == (2, 3, 4)

# ogrid — open (sparse) grid — efficient for broadcasting
r, c = np.ogrid[0:3, 0:4]        # r.shape (3,1), c.shape (1,4)

# indices — grid of indices
np.indices((3, 4))                 # shape (2, 3, 4)

Tiling and Repeating

np.tile([1, 2], 3)               # [1, 2, 1, 2, 1, 2]
np.tile([[1, 2]], (2, 3))        # 2×6 array

np.repeat([1, 2, 3], 2)         # [1, 1, 2, 2, 3, 3]
np.repeat([[1, 2]], [2, 3], axis=1)  # per-element repeat counts

From Buffers and Existing Memory

np.frombuffer(b"\x01\x02\x03", dtype=np.uint8)   # from bytes buffer
np.frombuffer(b"\x00\x00\x80\x3f", dtype=np.float32)  # → [1.0]

np.fromiter(range(5), dtype=int, count=5)         # from any iterable

# np.fromstring in text mode emits DeprecationWarning — instead use
# np.frombuffer (binary data, above) or np.loadtxt (text files, below):
np.array("1 2 3".split(), dtype=int)              # parse a string of numbers

np.fromfile("data.bin", dtype=np.float64)         # from binary file
np.fromfile("data.txt", dtype=float, sep="\n")    # from text file

Loading from Text / Files

np.loadtxt("data.csv", delimiter=",", dtype=float, skiprows=1)
np.genfromtxt("data.csv", delimiter=",", names=True, dtype=None, encoding="utf-8")

# Save and load NumPy binary format
np.save("arr.npy", a)
a = np.load("arr.npy")

np.savez("arrays.npz", x=a, y=b)        # multiple arrays
data = np.load("arrays.npz")
data["x"], data["y"]

np.savez_compressed("arrays.npz", x=a)  # compressed

Special Values

np.nan           # IEEE 754 NaN (float)
np.inf           # positive infinity
-np.inf          # negative infinity (np.NINF removed in NumPy 2.0)
0.0              # +0.0 (np.PZERO removed in NumPy 2.0)
-0.0             # -0.0 (np.NZERO removed in NumPy 2.0)
np.e             # Euler's number
np.pi            # π
np.euler_gamma   # Euler–Mascheroni constant

np.finfo(np.float64).eps       # machine epsilon ≈ 2.22e-16
np.finfo(np.float32).max       # max representable float32
np.iinfo(np.int32).max         # max int32 = 2147483647