Learn / NumPy
Intermediate

Shape Manipulation & Broadcasting

Reshaping, stacking, and the rule that lets mismatched shapes still add.

reshape relabels the same flat data into a new shape; it does not reorder data the way a transpose does. If you find yourself needing rows to become columns, that's .T / np.transpose, not reshape.

Broadcasting is how NumPy applies an operation to two arrays of different shapes without you writing a loop. Compare shapes from the right; two dimensions are compatible if they're equal, or one of them is 1 (it gets "stretched" to match). Play with the examples below.

FunctionEffectExample

np.concatenate([a, b], axis=0)

join along an existing axis

concatenate([[1,2],[3,4]])[1, 2, 3, 4] (1-D arrays)

np.vstack([a, b])

stack as rows

vstack([[1,2],[3,4]])[[1,2],[3,4]] (2 rows)

np.hstack([a, b])

stack side by side

hstack([[1,2],[3,4]])[1,2,3,4]

np.stack([a, b], axis=0)

join along a brand-new axis

stack([[1,2],[3,4]]) → shape (2, 2), a new leading axis

a.squeeze()

drop all size-1 dimensions

shape (1, 3, 1)(3,)

np.expand_dims(a, axis=0)

insert a new size-1 dimension

shape (3,)(1, 3)

Now practice it

Exercises that use what this lesson just covered.

Indexing & SlicingAggregations & Statistics