Skip to content
LearnPY
NumPy

Broadcasting and aggregation without loops

Combine arrays of different shapes, reduce values along an axis, and use keepdims to keep the dimensions you still need.

9 min readbeginnernumpy

By the end

  • Predict whether two array shapes can broadcast.
  • Add a row or column to a matrix without writing a loop.
  • Choose the right axis for sum, mean, and standard deviation.
  • Use keepdims to preserve a reduced axis for later arithmetic.

How broadcasting works

Broadcasting is NumPy's rule for combining arrays whose shapes differ. It compares shapes from right to left. A dimension of 1 can stretch to match the other side, and a missing leading dimension is treated as 1. If two dimensions are different and neither is 1, the operation fails.

Python

A row and a column broadcast in different directions

Ready
Loading editor…

Output

Press Run to execute this cell. The first run downloads Python; later runs reuse the session.

The row has shape (3,), which aligns with the matrix's last axis. NumPy reuses that row for both rows of the matrix. The column has shape (2, 1): its single column stretches across all three columns. In both cases, the smaller array is not copied by hand; NumPy applies the values logically during the operation.

Left shapeRight shapeResultWhy
(2, 3)(3,)(2, 3)Row repeats for each matrix row
(2, 3)(2, 1)(2, 3)Column repeats across columns
(2, 3)(1, 3)(2, 3)Leading 1 stretches to 2
(2, 3)(2,)errorRightmost 3 and 2 conflict
Common shape combinations

Aggregations and axes

Aggregations reduce an array to fewer values. Without an axis, a reduction collapses everything to one scalar. With an axis, it collapses only that axis and keeps the others. The axis you choose is the direction that disappears from the result.

Python

Totals, means, and variation along each axis

Ready
Loading editor…

Output

Press Run to execute this cell. The first run downloads Python; later runs reuse the session.

  • scores.sum() returns one number for the whole array.
  • scores.mean(axis=0) collapses rows and returns one mean per column.
  • scores.mean(axis=1) collapses columns and returns one mean per row.
  • scores.std(axis=1) returns the spread within each row.

Keep the dimension you need

A reduction normally removes the collapsed axis. That is fine when you only need the summary, but it can break the next broadcast. keepdims=True leaves the reduced axis in place with length 1, which is exactly the shape broadcasting can stretch.

Python

Center each row on its own mean

Ready
Loading editor…

Output

Press Run to execute this cell. The first run downloads Python; later runs reuse the session.

row_means has shape (2, 1), so subtracting it from scores with shape (2, 3) broadcasts one mean down each row. Without keepdims, row_means would have shape (2,), which would try to align the 2 with the 3 columns and fail.

Where broadcasting goes wrong

  • Adding a three-value array to a four-column matrix fails because 3 and 4 are neither equal nor 1.
  • Subtracting row means with shape (2,) from a (2, 3) matrix fails; use keepdims=True to get (2, 1).
  • Passing the wrong axis can give a correct-looking result with the wrong meaning, so check the result shape.
  • In-place operations such as arr += row change the original array; make a copy first if other code still needs it.

Practice

Make it stick

Run the tests as often as you like. Hints and the solution are available when you need them.

Exercise

Subtract each row's mean from that row. Keep the result in an array with the same shape as scores.

Your solution

Ready
Loading editor…

Results

Run the tests to check your solution. The first run downloads Python; later runs reuse the session.

Quiz

Check your understanding

01What is the shape of np.ones((3, 1)) + np.ones((1, 4))?
02What does matrix.mean(axis=1) return for a 2D matrix?
03Why use keepdims=True on a row-mean reduction?

Lesson progress