Reductions

A reduction summarizes many values into fewer values.

Common reductions include:

  • sum;
  • mean;
  • minimum;
  • maximum.

Reduce all values

The array has three values. The sum is 12. The mean is 4.0.

Reduce along an axis

For a matrix:

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

you can summarize columns or rows.

Row and column summaries

Runs locally with Python in your browser.

Ready to run.

Again, the named axis is the dimension being combined and removed:

  • axis=0 combines rows, producing one result per column;
  • axis=1 combines columns, producing one result per row.

Keep shape in mind

If A.shape is (2, 3), then:

A.sum(axis=0).shape

is (3,), because there are three columns.

A.sum(axis=1).shape

is (2,), because there are two rows.

Exercise: Column summary length

If A.shape is (2, 3), what is the shape of A.sum(axis=0)?

Answer it first, then check.

Hint

Reducing axis=0 removes the first shape entry and leaves the column count.

Solution

The shape is (3,). Starting from (2, 3), the reduction combines and removes axis 0, leaving one sum for each of the three columns.