NumPy Cheatsheet

Shape and Reshaping

Use this NumPy reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Inspecting Shape

import numpy as np

a = np.arange(24)
a.shape       # (24,)
a.ndim        # 1
a.size        # 24

b = a.reshape(4, 6)
b.shape       # (4, 6)
b.ndim        # 2

reshape

a = np.arange(12)

a.reshape(3, 4)         # view when possible, copy otherwise
a.reshape(3, -1)        # -1 infers the missing dimension → (3, 4)
a.reshape(-1, 4)        # → (3, 4)
a.reshape(-1)           # always 1-D (same as ravel with default order)
np.reshape(a, (3, 4))   # function form

a.reshape(3, 4, order="C")   # row-major (default)
a.reshape(3, 4, order="F")   # column-major (Fortran)

View vs copy: reshape returns a view if the array is contiguous; otherwise it copies. Check with result.base is a.

Flattening

MethodReturnsView?Order
a.ravel()1-Dview when possibleC (default)
a.ravel(order="F")1-Dview when possibleFortran
a.flatten()1-Dalways copyC (default)
a.flatten("F")1-Dalways copyFortran
b = np.array([[1, 2], [3, 4]])
b.ravel()       # [1, 2, 3, 4]   view
b.flatten()     # [1, 2, 3, 4]   copy
b.ravel("F")    # [1, 3, 2, 4]   column-major order

Adding and Removing Axes

a = np.array([1, 2, 3])    # shape (3,)

# Add an axis
a[np.newaxis, :]    # shape (1, 3)
a[:, np.newaxis]    # shape (3, 1)
np.expand_dims(a, axis=0)    # (1, 3)
np.expand_dims(a, axis=1)    # (3, 1)
np.expand_dims(a, axis=-1)   # (3, 1)
np.expand_dims(a, axis=(0, 2))  # multiple axes at once

b = np.array([[[1, 2, 3]]])   # shape (1, 1, 3)
np.squeeze(b)              # (3,)  — removes ALL size-1 axes
np.squeeze(b, axis=0)     # (1, 3)  — remove specific axis
np.squeeze(b, axis=(0,1)) # (3,)

Transposing and Permuting Axes

a = np.arange(24).reshape(2, 3, 4)

a.T                             # reverses axes: (4, 3, 2)
np.transpose(a)                 # same
np.transpose(a, axes=(1, 0, 2)) # custom permutation → (3, 2, 4)
np.moveaxis(a, 0, -1)           # move axis 0 to end → (3, 4, 2)
np.moveaxis(a, [0, 1], [-1, -2])  # move multiple
np.rollaxis(a, 2)               # roll axis 2 to front → (4, 2, 3) (legacy)
np.swapaxes(a, 0, 1)            # swap two axes → (3, 2, 4)

Stacking and Concatenating

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

np.concatenate([a, b])            # [1,2,3,4,5,6]  along axis 0
np.concatenate([a, b], axis=0)    # same
np.stack([a, b])                  # [[1,2,3],[4,5,6]]  new axis at 0
np.stack([a, b], axis=1)          # [[1,4],[2,5],[3,6]]  new axis at 1
np.vstack([a, b])                 # vertical stack → [[1,2,3],[4,5,6]]
np.hstack([a, b])                 # horizontal stack → [1,2,3,4,5,6]
np.dstack([a, b])                 # depth stack → [[[1,4],[2,5],[3,6]]]

# 2-D examples
m = np.array([[1, 2], [3, 4]])
n = np.array([[5, 6]])
np.vstack([m, n])                 # (3, 2)
np.hstack([m, m])                 # (2, 4)
np.concatenate([m, m], axis=1)    # same as hstack for 2-D

# Block assembly (NumPy ≥ 1.13)
np.block([[m, m],
          [n, n]])                # (3, 4) block matrix

Performance note

np.concatenate is fastest for large arrays; np.stack / vstack / hstack are convenience wrappers around it.

Splitting

a = np.arange(12)
np.split(a, 3)            # [array([0,1,2,3]), array([4,5,6,7]), array([8,9,10,11])]
np.split(a, [3, 7])       # split at indices 3 and 7 → 3 pieces

b = np.arange(16).reshape(4, 4)
np.vsplit(b, 2)           # split into 2 row-groups
np.hsplit(b, 2)           # split into 2 col-groups
np.dsplit(c, 2)           # split along depth (3-D)
np.array_split(a, 3)      # allows unequal splits (no error)

Tiling and Repeating

np.tile(a, 3)             # repeat array 3 times along axis 0
np.tile(a, (2, 3))        # 2 times vertically, 3 times horizontally
np.repeat(a, 2)           # repeat each element: [0,0,1,1,2,2,...]
np.repeat(a, [1, 2, 1])   # per-element repeat counts

Broadcasting-Friendly Reshaping Patterns

row = np.array([1, 2, 3])          # (3,)
col = np.array([10, 20, 30])       # (3,)

# outer sum via reshape
row[np.newaxis, :] + col[:, np.newaxis]   # (3, 3) — each row+col pair

# batch matrix multiply prep
A = np.ones((5, 3, 4))    # batch of 5 matrices
B = np.ones((4, 2))       # single matrix
A @ B                      # (5, 3, 2)  — B broadcast over batch dim