Sub topic 3
Mean, Median, and Standard Deviation Along an Axis
Assume you know basic Python, can create NumPy arrays, and understand indexing and shape. In NumPy, an axis is a direction in an array. For a two-dimensional array, axis 0 runs down rows, while axis 1 runs across columns.
Statistics Along an Axis
Statistical aggregations reduce values along an axis:
| Function | Purpose |
|---|---|
| `mean` | Arithmetic average |
| `median` | Middle value after sorting |
| `std` | Standard deviation, or spread around the mean |
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.mean(axis=0)) # [2.5 3.5 4.5]
print(np.median(a, axis=1)) # [2. 5.]
print(a.std(axis=0)) # [1.5 1.5 1.5]The reduced axis disappears. Therefore, a.mean(axis=0) has shape (3,), and a.mean(axis=1) has shape (2,).
Finding Extreme Values
argmax and argmin return positions, not the extreme values themselves. For axis=1, each result contains one column index per row.
print(a.argmax(axis=1)) # [2 2]
print(a.argmin(axis=0)) # [0 0 0]Ties return the first matching index.
Three Dimensions and Tuples of Axes
For b.shape == (2, 3, 4), axis=0 removes the first dimension. A tuple reduces several dimensions at once.
b = np.arange(24).reshape(2, 3, 4)
print(b.mean(axis=2).shape) # (2, 3)
print(b.sum(axis=(0, 2)).shape) # (3,)Missing Values and Running Totals
A normal aggregation propagates NaN, a floating-point marker for missing data. Use nanmean, nansum, and related functions to skip missing entries.
cumsum is cumulative, rather than reducing. It keeps the shape and records a running total.
c = np.array([[1.0, np.nan],
[3.0, 4.0]])
print(np.nanmean(c, axis=0)) # [2. 4.]
print(np.cumsum(np.nan_to_num(c), axis=1))
# [[1. 1.]
# [3. 7.]]Data Types and Common Mistakes
Small integer types can overflow during sums. Choose a wider dtype when necessary, such as a.sum(dtype=np.int64). Also check whether you intended rows or columns, and predict the result shape before writing the next operation.
Exercise
For an array with shape (4, 5), what is the shape of x.std(axis=1)?
Show answer
(4,), because axis 1 is removed and one statistic remains for each row.