stack(), hstack(), vstack() (NumPy)
These functions combine arrays: np.stack joins them along a brand-new axis, while np.hstack stacks horizontally (column-wise) and np.vstack stacks vertically (row-wise) along existing axes.
NumPy
vstack puts arrays on top of each other, adding rows, and is great for assembling 1-D rows into a matrix. hstack lays them side by side, adding columns. Both operate along existing dimensions, so the result keeps the same number of dimensions as concatenate would give.
stack is different: it introduces a new axis. Stacking three 1-D arrays of length 4 with np.stack gives a (3, 4) array, where each input becomes a row along the new leading axis. Use the axis argument to choose where that new dimension goes.
Reach for vstack/hstack when you think in rows and columns, and for stack when you specifically want to add a dimension. The general workhorse beneath them all is concatenate.
Syntax
np.vstack([a, b]) | np.hstack([a, b]) | np.stack([a, b], axis=0)Examples
Python
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
print(np.vstack([a, b]))Output:
[[1 2]
[3 4]]