Aggregations: sum, mean, axis

Reviewed & published by Brayan K

An aggregation is a NumPy operation that reduces an array of many values into a single summary statistic — sum, mean, minimum, maximum, or standard deviation — all computed at C speed.

Part of the free NumPy course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

In this lesson you'll master the core aggregation methods and the powerful axis argument that lets you summarize a 2D array per-column or per-row, plus argmax, argmin, and cumulative sums.

What You'll Learn in This Lesson

1 The Core Aggregations

Every NumPy array carries a set of methods that collapse it to a single number. The most common are sum(), mean(), min(), max(), and std() (standard deviation). Called with no arguments, they work across the entire array.

import numpy as np

arr = np.array([2, 4, 6, 8, 10])

print(arr.sum())    # 30
print(arr.mean())   # 6.0
print(arr.min())    # 2
print(arr.max())    # 10
print(arr.std())    # 2.8284271247461903

# ✅ Expected output:
# 30
# 6.0
# 2
# 10
# 2.8284271247461903

Expected output: 30, 6.0, 2, 10, and 2.8284271247461903 for the standard deviation.

2 The axis Argument: 0 vs 1

With a 2D array you usually want a result per column or per row, not one number for everything. The axis argument controls this. The simplest rule: axis is the dimension that disappears.

🧭 Reading the axes of a 2D array:

import numpy as np

grid = np.array([[1, 2, 3],
                 [4, 5, 6]])      # shape (2, 3)

# Whole array
print(grid.sum())            # 21

# axis=0 -> down the columns -> one sum per column
print(grid.sum(axis=0))      # [5 7 9]

# axis=1 -> across the rows -> one sum per row
print(grid.sum(axis=1))      # [ 6 15]

# ✅ Expected output:
# 21
# [5 7 9]
# [ 6 15]

Expected output: 21 for the whole grid, [5 7 9] per column (axis=0), and [6 15] per row (axis=1).

3 Mean Per Column and Per Row

The axis argument works the same way for every aggregation. Here we compute the average of each subject (column) and each student (row) from a small grade table.

import numpy as np

# rows = students, columns = math, science, english
grades = np.array([[90, 80, 70],
                   [60, 70, 80],
                   [100, 90, 80]])

# Average per subject (down the columns)
print(grades.mean(axis=0))   # [83.33333333 80.         76.66666667]

# Average per student (across the rows)
print(grades.mean(axis=1))   # [80. 70. 90.]

# Highest single grade anywhere, and lowest
print(grades.max())          # 100
print(grades.min(axis=1))    # [70 60 80]

# ✅ Expected output:
# [83.33333333 80.         76.66666667]
# [80. 70. 90.]
# 100
# [70 60 80]

Expected output: subject averages [83.33 80. 76.67], student averages [80. 70. 90.], overall max 100, and the per-student minimums [70 60 80].

4 argmax, argmin, and cumsum

Sometimes you need the position of an extreme value, not the value itself. np.argmax returns the index of the largest element and np.argmin the index of the smallest. cumsum gives a running total — each element is the sum of everything up to and including it.

import numpy as np

scores = np.array([12, 45, 7, 88, 23])

print(np.argmax(scores))   # 3   (88 is the largest, at index 3)
print(np.argmin(scores))   # 2   (7 is the smallest, at index 2)

# Running total: 12, 12+45, ...
print(np.cumsum(scores))   # [ 12  57  64 152 175]

# argmax also takes an axis on 2D arrays
grid = np.array([[1, 9, 3],
                 [7, 2, 8]])
print(np.argmax(grid, axis=1))   # [1 2]  (index of max in each row)

# ✅ Expected output:
# 3
# 2
# [ 12  57  64 152 175]
# [1 2]

Expected output: 3, 2, the running total [12 57 64 152 175], and [1 2] for the per-row argmax.

🎯 YOUR TURN: Fill in the Blanks

Replace each ___ so the program reports the total of each column and the average overall.

import numpy as np

sales = np.array([[10, 20],
                  [30, 40],
                  [50, 60]])

# Total of each COLUMN -> collapse the rows
col_totals = sales.sum(axis=___)      # fill in 0 or 1

# Average of every value in the array
overall_avg = sales.___()             # fill in the method name

print(col_totals)    # Expected output: [ 90 120]
print(overall_avg)   # Expected output: 35.0

Expected output: [ 90 120] and 35.0. (Answers: 0, mean.)

⚠️ Common Errors & Quick Reference

❌ Got per-row results when you wanted per-column

You passed the wrong axis — they are easy to swap.

✅ Fix: remember axis is the dimension that disappears. Use axis=0 for per-column, axis=1 for per-row.

❌ Confused max with argmax

max returns the value; argmax returns the index.

✅ Fix: use argmax/argmin only when you need the position of the extreme value.

TaskCode
Total of whole arrayarr.sum()
Per-column sumarr.sum(axis=0)
Per-row meanarr.mean(axis=1)
Index of maxnp.argmax(arr)
Running totalnp.cumsum(arr)

🏆 Mini Challenge: Best Performing Store

Each row is a store and each column is a month. Find the total revenue per store, then identify which store earned the most.

import numpy as np

# rows = stores, columns = Jan, Feb, Mar
revenue = np.array([[100, 120, 130],
                    [200, 210, 190],
                    [ 90, 110, 100]])

store_totals = revenue.sum(axis=1)
print(store_totals)            # [350 600 300]

best = np.argmax(store_totals)
print("Best store index:", best)   # Best store index: 1

# ✅ Expected output:
# [350 600 300]
# Best store index: 1

❓ Frequently Asked Questions

Lesson complete — you can summarize any array!

You now reach for sum, mean, min, max, and std with confidence, control direction with axis, and locate extremes with argmax and argmin.

Practice quiz

What does np.array([2, 4, 6, 8, 10]).sum() return?

  • 20
  • 30
  • 6.0
  • 10

Answer: 30. Adding 2+4+6+8+10 gives 30.

For grid = [[1, 2, 3], [4, 5, 6]], what is grid.sum(axis=0)?

  • [6 15]
  • 21
  • [5 7 9]
  • [1 4]

Answer: [5 7 9]. axis=0 collapses the rows, giving one column sum each: [5 7 9].

For grid = [[1, 2, 3], [4, 5, 6]], what is grid.sum(axis=1)?

  • [5 7 9]
  • [6 15]
  • 21
  • [3 12]

Answer: [6 15]. axis=1 collapses the columns, giving one row sum each: 6 and 15.

Which call returns one value per column of a 2D array?

  • arr.sum()
  • arr.sum(axis=1)
  • arr.sum(axis=0)
  • arr.cumsum()

Answer: arr.sum(axis=0). axis=0 removes the row dimension, leaving a per-column result.

What does np.argmax(np.array([12, 45, 7, 88, 23])) return?

  • 88
  • 4
  • 3
  • 45

Answer: 3. argmax returns the index of the largest value; 88 sits at index 3.

What is the difference between max and argmax?

  • They are identical
  • max gives the value, argmax gives its index
  • max gives the index, argmax gives the value
  • argmax only works on 1D arrays

Answer: max gives the value, argmax gives its index. max returns the largest value while argmax returns its position.

What does np.cumsum(np.array([12, 45, 7])) return?

  • [12 57 64]
  • 64
  • [12 45 7]
  • [7 45 12]

Answer: [12 57 64]. Each element is the running total: 12, 12+45=57, 57+7=64.

What does the mean of [[90,80,70],[60,70,80],[100,90,80]] along axis=1 return?

  • [83.33 80. 76.67]
  • 100
  • [80. 70. 90.]
  • [90 60 100]

Answer: [80. 70. 90.]. axis=1 averages across each row (student): 80, 70, and 90.

Called with no axis argument, arr.sum() returns what?

  • One total per column
  • One total per row
  • A 2D array
  • A single scalar over the whole array

Answer: A single scalar over the whole array. Without an axis, the aggregation reduces the entire array to one number.

Which method computes the standard deviation of an array?

  • arr.std()
  • arr.var()
  • arr.cumsum()
  • arr.argmin()

Answer: arr.std(). std() returns the standard deviation; for [2,4,6,8,10] it is about 2.83.

Continue this course

Frequently asked questions

What is an aggregation in NumPy?

An aggregation is a function that reduces many values down to a single summary number, such as sum, mean, min, max, or std (standard deviation). NumPy runs these in fast compiled C code, so summarizing even huge arrays is nearly instant.

What does the axis argument do?

The axis argument controls the direction an aggregation collapses in a multi-dimensional array. axis=0 collapses the rows and produces one value per column, while axis=1 collapses the columns and produces one value per row. With no axis, NumPy aggregates over the entire array and returns a single scalar.

How do I remember axis=0 vs axis=1?

Think of axis as the dimension that disappears. axis=0 removes the row dimension, so you are left with column-wise results. axis=1 removes the column dimension, so you are left with row-wise results. A handy phrase: axis=0 goes down the columns, axis=1 goes across the rows.

What is the difference between argmax and max?

max returns the largest value in the array, while argmax returns the index (position) of that largest value. Use argmax when you need to know where the maximum is, for example to find which category scored highest.