Sub topic 1
NumPy Aggregations Along Rows and Columns
Prerequisites
Assume you know basic Python, can create NumPy arrays, and understand an array's shape and indexing.
Array shape and what an axis is
A NumPy array has a shape that describes its dimensions. For example, an array with shape (2, 3) has 2 rows and 3 columns:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape) # (2, 3)An axis is one direction through an array. In this two-dimensional array, axis 0 is the row direction, and axis 1 is the column direction.
Reducing an array to a single value
An aggregation, also called a reduction, combines many values into fewer values. Functions such as sum, mean, min, and max perform aggregations.
Without an axis, NumPy combines every value:
print(a.sum()) # 21
print(a.mean()) # 3.5
print(a.min()) # 1
print(a.max()) # 6The result of a.sum() is a scalar, which is a single value.
Choosing a direction with axis
Use axis=0 to combine values vertically, down the rows. Each column produces one result. Use axis=1 to combine values horizontally, across the columns. Each row produces one result.
Column totals and row totals
print(a.sum(axis=0)) # [5 7 9]
print(a.sum(axis=1)) # [ 6 15]
print(a.mean(axis=0)) # [2.5 3.5 4.5]
print(a.max(axis=1)) # [3 6]The shape confirms the rule:
a.sum(axis=0)has shape(3,), one value for each column.a.sum(axis=1)has shape(2,), one value for each row.
Predict the retained dimension before running an aggregation. This prevents many axis mistakes.
Exercise
What are the values and shape of a.min(axis=0) for the array above?
Show answer
The values are [1 2 3], and the shape is (3,), because one minimum remains for each column.