sum, mean, median, min & max
Collapse a whole array of scores into one number with sum, mean, median, min and max — and learn the function form vs the method form.
Watch the lesson
1 video on CodeWithMunnaX
After an IPL season you have hundreds of numbers: runs in every match, balls faced, wickets. Nobody reads them one by one. A captain asks short questions — "How many runs did Virat score in total? What is his average? What was his best score?" Each answer collapses many numbers into one. In NumPy these are called aggregate functions (or reductions), and they run in fast C code instead of a Python loop.
Definition
An aggregate function (also called a reduction) takes an array of many values and reduces it to a smaller result — a single number for the whole array, or one number per row/column when you pass
axis. The core ones aresum,mean,median,minandmax.
- Reduces — the output has fewer elements than the input. 10 match scores go in, 1 total comes out.
- Whole array by default — with no
axis, NumPy treats a 2D array as one big bag of numbers. - Vectorized — the loop happens inside NumPy's compiled code, so
arr.sum()on a million values is far faster than Python'sforloop.
| Function | What it answers | Cricket question |
|---|---|---|
sum | total of all values | total runs in the season |
mean | arithmetic average = sum ÷ count | batting average per match |
median | middle value after sorting | a "typical" innings, ignoring one huge century |
min | smallest value | lowest score (a duck = 0) |
max | largest value | highest score |
Syntax
Most aggregates come in two forms that do exactly the same thing:
python
np.sum(a, axis=None, dtype=None, keepdims=False) # function form
a.sum(axis=None, dtype=None, keepdims=False) # method form
np.mean(a, axis=None) a.mean(axis=None)
np.min(a, axis=None) a.min(axis=None) # np.amin is an old alias
np.max(a, axis=None) a.max(axis=None) # np.amax is an old alias
np.median(a, axis=None) # function form ONLY — there is no a.median()| Parameter | Meaning | Default |
|---|---|---|
a | the input array (or anything array-like, e.g. a Python list) | — required |
axis | which direction to reduce: None = whole array, 0 = down the columns, 1 = across the rows | None |
dtype | type used for the calculation/result, e.g. np.float64 | depends on input |
keepdims | keep the reduced axis as size 1 (useful for broadcasting) | False |
Note: the function form
np.sum(x)also works on a plain Python list (NumPy converts it first). The method formx.sum()only works whenxis already a NumPy array.
Example — Virat's season in five numbers
python
import numpy as np
virat = np.array([72, 45, 88, 31, 64, 0, 103, 52, 19, 77])
print("Total runs :", virat.sum())
print("Average :", virat.mean())
print("Median :", np.median(virat))
print("Lowest :", virat.min())
print("Highest :", virat.max())
print("Matches :", virat.size)text
Total runs : 551
Average : 55.1
Median : 58.0
Lowest : 0
Highest : 103
Matches : 10How it works: sum adds all 10 scores (551). mean divides that by the count (551 ÷ 10 = 55.1). median sorts the scores and takes the middle — with 10 values there are two middle values (52 and 64), so it averages them: 58.0. min and max pick the duck and the century.
Example — function form vs method form
python
import numpy as np
virat = np.array([72, 45, 88, 31, 64, 0, 103, 52, 19, 77])
print(np.sum(virat), virat.sum()) # same answer
print(np.max(virat), virat.max()) # same answer
print(np.sum([10, 20, 30])) # function form accepts a plain list
print(type(virat.sum())) # a NumPy integer scalar
print(type(virat.mean())) # mean is always a floattext
551 551
103 103
60
<class 'numpy.int64'>
<class 'numpy.float64'>How it works: both forms call the same C code. Notice the types: summing integers gives a NumPy integer (np.int64), but mean always returns a float (np.float64) because an average is usually not a whole number.
Mean vs median — why we need both
The mean is pulled towards extreme values; the median is not. Look at a batter who scored one big century and failed in the rest:
python
import numpy as np
scores = np.array([12, 8, 15, 10, 150])
print("mean :", scores.mean())
print("median:", np.median(scores))text
mean : 39.0
median: 12.0The mean (39.0) suggests he scores almost 40 every match — misleading. The median (12.0) says his typical innings is about 12. When data has outliers, report the median too.
Example — aggregates on 2D data
python
import numpy as np
# rows = players, columns = matches
scores = np.array([
[72, 45, 88, 31, 64], # Virat
[56, 0, 74, 88, 32], # Rohit
[45, 32, 0, 67, 18], # Hardik
[33, 61, 45, 0, 77], # Shubman
])
print("Squad total :", scores.sum())
print("Squad average:", scores.mean())
print("Best score :", scores.max())
print("Per player :", scores.sum(axis=1))text
Squad total : 928
Squad average: 46.4
Best score : 88
Per player : [300 250 162 216]How it works: without axis, the 4×5 table is treated as 20 numbers. With axis=1 you get one total per player (row). The axis parameter is so important that it has its own topic next.
Other useful aggregates
| Function | Meaning | Example result for [2, 3, 4] |
|---|---|---|
np.prod / a.prod() | multiply all values | 24 |
np.ptp(a) | "peak to peak" = max − min (the range) | 2 |
np.average(a, weights=w) | weighted mean | depends on w |
a.size / len(a) | how many values (count) | 3 |
np.any(a > 3) / np.all(a > 1) | is any / are all values True? | True / True |
Note: in NumPy 2.x the method
a.ptp()was removed — use the functionnp.ptp(a)or simplya.max() - a.min().
Common mistakes
- ❌
virat.median()→AttributeError: 'numpy.ndarray' object has no attribute 'median'. ✅np.median(virat)— median has only a function form. - ❌ Using Python's built-in
sum(scores)on a 2D array — it adds the rows together and returns an array, not one number. ✅ Usescores.sum()ornp.sum(scores). - ❌ Using built-in
max()/min()on big arrays — they loop in slow Python and fail on 2D arrays. ✅ Usearr.max()/arr.min(). - ❌ Reporting only the mean when there are outliers (one 150 among small scores). ✅ Check the median as well.
- ❌ Writing
virat.sumwithout brackets — you get the method object, not the total. ✅virat.sum().
Comparison — Python list vs NumPy
| Task | Python list | NumPy array |
|---|---|---|
| Total | sum(runs) | runs.sum() |
| Average | sum(runs) / len(runs) | runs.mean() |
| Median | statistics.median(runs) | np.median(runs) |
| Per-row totals of a table | a loop or list comprehension | table.sum(axis=1) |
| Speed on 1 million values | slow (Python loop) | very fast (C loop) |
Interview tip
Q: Why is there arr.mean() but no arr.median()?
A: The median needs a partial sort of the data, and NumPy only exposes it as the function np.median(). Functions like sum, mean, min, max, std, var, prod, argmin and argmax exist in both forms; median, percentile, quantile and ptp are function-only.
Key points to remember
- An aggregate (reduction) collapses many values into fewer — one number for the whole array, or one per row/column with axis.
- sum, mean, min and max exist as both a function (np.sum(a)) and a method (a.sum()); both give the same result.
- median exists ONLY as a function: np.median(a). a.median() raises AttributeError.
- mean always returns a float; sum of an integer array returns an integer.
- The mean is pulled by outliers; the median is the middle value and is robust to one huge score.
- Range = np.ptp(a) or a.max() - a.min(); the ptp method was removed in NumPy 2.
- Prefer NumPy's aggregates over Python's built-in sum/min/max — they are faster and understand 2D arrays.
Try it yourself
Season summary for one batter
Mean vs median with an outlier
Function form vs method form
Practice: summarise Rohit's season
Revision Flashcards
Tap a card to flip it and see the answer.
