Thuta Learning
IntermediateData & Databasesintermediate

Aggregations

Relax. We'll talk through this in plain words — no textbook voice.

Aggregation means computing a single summary value, or a row/column summary, from a batch of data in an array. sum, min, max, mean, median, std are tools you'll reach for constantly in data analysis.

python
import numpy as np

sales = np.array([
    [120, 135, 150],
    [160, 155, 180]
])

print("Total sales:", sales.sum())
print("Average sales:", sales.mean())
print("Highest sale:", sales.max())
print("Column totals:", sales.sum(axis=0))
print("Row totals:", sales.sum(axis=1))

sales.sum() adds up every element. axis=0 means computing column-wise, and axis=1 means computing row-wise. Understanding axis is essential whenever you need row/column summaries.

You should see
Total sales: 900 Average sales: 150.0 Highest sale: 180 Column totals: [280 290 330] Row totals: [405 495]

Info

If axis is hard to remember, think of it this way: axis=0 cuts across the rows and produces a column result. axis=1 cuts across the columns and produces a row result.

Easy traps

  • If you want row totals but use axis=0, you'll end up with column totals instead. Check the output shape to confirm it's actually what you wanted.

Exercise

Aggregation plus axis really shines for things like computing each student's average, or each subject's average.

python
import numpy as np

exam_scores = np.array([
    [80, 75, 90],
    [88, 92, 85],
    [70, 78, 82]
])

student_average = exam_scores.mean(axis=1)
subject_average = exam_scores.mean(axis=0)

print("Student averages:", student_average)
print("Subject averages:", subject_average)

You'll know it worked when: Student averages: [81.66666667 88.33333333 76.66666667] Subject averages: [79.33333333 81.66666667 85.66666667]

Aggregations | Thuta Learning