ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

NumPy Tutorial• 7 min read

Aggregations & Axis Operations: sum, mean, std, argmax

Mastering the axis parameter: axis=0 (down columns) vs axis=1 (across rows)

Aggregation functions collapse dimensions along specified axes to compute summary statistics such as sum, mean, variance, and extreme values.

Understanding the Axis Parameter

No axis specified (arr.sum()): Collapses the entire array into a single scalar value.

axis=0: Collapses along the first dimension (collapses rows, computing column-wise totals).

axis=1: Collapses along the second dimension (collapses columns, computing row-wise totals).

np.argmax(arr, axis=...): Returns the integer indices of the maximum values along an axis, crucial for reading classification model outputs.

Column-wise vs Row-wise Aggregation
import numpy as np

# 3 students (rows), 4 exam scores (columns)
grades = np.array([
    [85, 90, 78, 92],
    [70, 75, 80, 85],
    [95, 98, 92, 100]
])

print("Overall class mean:       ", round(grades.mean(), 2))
print("Exam averages (axis=0):   ", grades.mean(axis=0))
print("Student averages (axis=1):", grades.mean(axis=1))
print("Top scorer per exam:      ", grades.argmax(axis=0))
axis=0 aggregates down columns; axis=1 aggregates across rows.
Pro Tip

Remember: the axis specified is the dimension that gets collapsed (eliminated) in the output shape.

ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

When computing the mean of a 2D matrix of shape (100, 5) with `arr.mean(axis=0)`, what is the shape of the result?