Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 49 ยท Array Math

Aggregations and Axes

Summarize NumPy arrays with sum, mean, min, max, std, cumsum, argmax, median and percentile, understand the axis and keepdims arguments, and handle NaN safely.

Raw numbers are rarely the answer; summaries are. "What was the total?", "What is the average per column?", "Which day had the highest value?" NumPy answers all of these with aggregation functions (also called reductions) that collapse many values into fewer ones.

The part that confuses almost everyone at first is the axis argument, which says which direction to collapse. This lesson explains axes with a picture, covers the everyday statistics (sum, mean, min, max, std, var), cumulative versions, position finders (argmin, argmax), robust statistics (median, percentile, quantile), keepdims, and the NaN-aware variants.

The basic reductions

Called with no extra arguments, a reduction treats the array as one flat list and returns a single number. You can use either the method form (a.sum()) or the function form (np.sum(a)).

Python Whole-array summaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

By default std and var divide by N (the population formula). For a sample estimate, pass ddof=1; this and other statistics are covered in Statistics, Correlation and Covariance.

What axis means

axis names the dimension that disappears. For a 2D array of shape (rows, columns):

  • axis=0 collapses the rows, giving one result per column.
  • axis=1 collapses the columns, giving one result per row.
flowchart TB
    T["a: shape (2, 3)<br/>row0: 4 8 15<br/>row1: 16 23 42"]
    T --> A0["axis=0: combine down each column<br/>sum = 20 31 57<br/>shape (3,)"]
    T --> A1["axis=1: combine across each row<br/>sum = 27 81<br/>shape (2,)"]

The axis you name is the one that gets squashed away; the other axis survives.

Python Axis 0 versus axis 1

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A handy memory aid: the shape loses the axis you chose. (2, 3) with axis=0 leaves (3,); with axis=1 leaves (2,). For 3D arrays the same rule applies, and you can even pass a tuple such as axis=(0, 2) to collapse two axes at once.

Python Axes of a 3D array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

keepdims: keep the axis as size 1

After a reduction the collapsed axis is gone, which sometimes makes the result hard to combine with the original. keepdims=True keeps that axis with length 1, so the result still broadcasts against the input (see Broadcasting).

Python Normalizing rows with keepdims

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without keepdims, counts / counts.sum(axis=1) would raise a shape error for this input, because the row totals would have shape (2,) instead of (2, 1).

Cumulative functions

cumsum and cumprod do not collapse the array. They return a running total (or product) of the same shape, and the axis argument says in which direction to accumulate. Without an axis they work on the flattened array.

Python Running totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Where is it? argmin and argmax

argmax and argmin return the index of the largest and smallest value. On a multi-dimensional array without an axis they index the flattened array; use np.unravel_index to turn that back into coordinates. With an axis you get one index per row or column. When values tie, the first occurrence wins.

Python Positions of extremes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Median, percentile and quantile

The mean is sensitive to outliers; the median (the middle value) is not. np.percentile(a, q) takes q between 0 and 100, and np.quantile(a, q) takes q between 0 and 1. Both interpolate linearly between neighbours by default. Note that median, percentile and quantile exist as functions only (np.median(a)), not as array methods.

Python Robust statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

One extreme salary drags the mean to about 90 while the median stays at 40. The last lines use the interquartile range (IQR) rule to flag values far above the upper quartile, a common outlier check that combines aggregation with a boolean mask.

NaN-aware aggregations

If an array contains nan, an ordinary reduction returns nan, because "not a number" is contagious. NumPy provides nan-prefixed twins that skip missing values: nansum, nanmean, nanmin, nanmax, nanstd, nanmedian, nanargmax and more.

Python Skipping missing values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Using a nan function silently ignores the missing entries, so count them first if their number matters. A full treatment, including masked arrays and filling strategies, is in Missing Data and NaN.

Note: Reductions on integer arrays use a wide integer for sum and prod, but they do not warn when values overflow. For large totals, ask for a bigger accumulator with dtype=, for example a.sum(dtype=np.int64) or a.sum(dtype=float).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For an array a of shape (4, 6), what is the shape of a.sum(axis=0)?

    axis=0 collapses the first axis (the 4 rows), leaving one total per column, so the shape is (6,).
  2. 2. What does keepdims=True do?

    The reduced axis stays as length 1, which makes results like row totals directly usable in a / totals.
  3. 3. np.array([3, 9, 9, 1]).argmax() returns:

    argmax returns an index, not a value, and for ties it returns the first occurrence, which is index 1.
  4. 4. Why prefer np.median over np.mean for data with a few extreme outliers?

    The median depends only on the middle of the sorted data, so a single huge value does not move it, while it pulls the mean strongly.
  5. 5. What does np.sum return for an array containing a nan?

    Any arithmetic with nan gives nan. Use np.nansum to ignore missing values.

Summary

  • Reductions such as sum, mean, min, max, std, var, prod and np.ptp collapse an array to one number, or fewer dimensions when you pass axis.
  • axis names the dimension that disappears: axis=0 gives one result per column, axis=1 one per row; tuples collapse several axes.
  • keepdims=True preserves the collapsed axis as size 1 for easy broadcasting.
  • cumsum and cumprod keep the shape and accumulate; argmin and argmax return positions (first occurrence on ties).
  • np.median, np.percentile and np.quantile give robust summaries and quartile-based outlier checks.
  • The nan versions (nansum, nanmean, ...) skip missing values; plain reductions return nan.

Next: compare arrays safely and learn why 0.1 + 0.2 == 0.3 is false in Comparing Arrays and Floating Point.