Write Python. Understand every error.

Starting Python in your browser…

NumPy · topic 21 of 25

Statistics and aggregation

Aggregation functions summarise an array in a single value. Each one exists both as a method and as a function, so a.sum() and np.sum(a) are the same.

  • sum, mean, min, max, prod
  • std (standard deviation) and var (variance)
  • np.median(a) and np.percentile(a, q)
  • argmin and argmax give the position of the smallest and largest value

On a 2D array, the axis argument chooses the direction. Think of axis as the dimension that disappears.

  • axis=0 works down each column, giving one result per column
  • axis=1 works across each row, giving one result per row
  • no axis uses every element and gives one number
marks = np.array([[60, 70, 80],
                  [50, 90, 75]])
print(marks.mean(axis=0))   # each subject: [55.  80.  77.5]
print(marks.sum(axis=1))    # each student: [210 215]

For ordering data, np.sort(a) returns a sorted copy, np.argsort(a) gives the positions that would sort it, and np.unique(a) returns the distinct values in order. With return_counts=True it also counts them. np.cumsum(a) gives a running total.

Key takeaways

  • sum, mean, min, max, std and var summarise an array, and np.median(a) gives the middle value.
  • argmin and argmax give the position of the smallest and the largest value.
  • axis=0 works down each column and axis=1 works across each row.
  • Without axis, the result covers the whole array.

Common mistakes

  • Mixing up the axes. axis=0 gives one result per column, not per row.
  • Expecting argmax to return the largest value. It returns the position of that value.

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.