Reshaping, stacking and splitting
reshape, transpose, concatenate and split — how to move data between shapes without copying more than necessary.
Reshape and transpose
reshape returns a new view when the data is contiguous, so it is cheap. -1 means "work this dimension out for me".
a = np.arange(12)
a.reshape(3, 4)
a.reshape(3, -1) # -1 -> 4
a.reshape(-1, 6) # -1 -> 2
a.ravel() # flatten (view when possible)
m = np.arange(6).reshape(2, 3)
m.T # transpose: (3, 2)
m.T.shape
m.flatten() # always a copy⚠️
reshape cannot invent or discard elements: the product of the new shape must equal the old size. "cannot reshape array of size 10 into shape (3,4)" is telling you the arithmetic does not match, not that NumPy is broken.Stacking and concatenating
| Function | Effect |
|---|---|
np.concatenate([a, b], axis=0) | Join along an existing axis |
np.vstack([a, b]) | Stack rows (adds a dimension if needed) |
np.hstack([a, b]) | Stack columns |
np.stack([a, b]) | New axis — turns two (3,) into (2, 3) |
np.column_stack([a, b]) | Two 1-D arrays become an (n, 2) table |
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.concatenate([a, b]) # array([1, 2, 3, 4, 5, 6])
np.stack([a, b]) # shape (2, 3)
np.column_stack([a, b]) # shape (3, 2) - a tidy two-column tableThe distinction that matters: concatenate joins existing arrays, stack creates a new dimension. Choosing the wrong one is why a merged dataset suddenly has the wrong number of dimensions.
Splitting and masking shapes
m = np.arange(12).reshape(3, 4)
np.split(m, 3) # three (1, 4) pieces
np.hsplit(m, 2) # split columns
top, bottom = np.vsplit(m, [2]) # rows 0-1, then 2
np.newaxis # add an axis
v = np.array([1, 2, 3])
v[:, None].shape # (3, 1)
v[None, :].shape # (1, 3)FAQ
reshape or resize?
reshape returns a new array/view and never changes the original in place; resize changes the array itself (and pads with zeros if it grows). Prefer reshape.How do I append to a NumPy array?
Not in a loop —
np.append copies the whole array every call. Build a Python list, then call np.array(list) (or np.stack) once at the end.Related
NumPy arrays Indexing, slicing and masks
Last refreshed 2026-09-18.