NumPy Aggregation, Statistics and Sorting: sum, axis, percentile, argsort
Turn many values into a few answers: totals, averages, spread, running totals, percentiles, sorting and counting. With the one rule that clears up the axis parameter: the axis you name disappears.
What you will learn
- Summarise an array with sum, mean, median, var, std, argmax and argmin
- Predict what axis=0 and axis=1 return: the axis you name disappears
- Use cumsum, diff, percentile, quantile and the nan-safe functions
- Order data with sort and argsort, and count with unique and conditions
Before you start
- NumPy arrays, shape and dtype
- NumPy ufuncs and broadcasting
Think about a till receipt. Five prices, one under the other, and at the bottom they slide together into one line: the total. Ask a different question, like the biggest price or the average, and the same five prices give a different single answer. That's aggregation: many values go in, one answer comes out.
Most data work comes down to exactly that. In this lesson you'll summarise arrays, keep running totals, find where values sit, and put things in order. You'll also clear up the axis parameter, which confuses almost everyone at first.
Sum, mean and spread
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print("sum :", np.sum(a))
print("prod :", np.prod(a))
print("min :", np.min(a))
print("max :", np.max(a))
print("mean :", np.mean(a))
print("median:", np.median(a))
print("var :", np.var(a))
print("std :", np.std(a))
sum : 150
prod : 12000000
min : 10
max : 50
mean : 30.0
median: 30.0
var : 200.0
std : 14.142135623730951
The mean adds everything and divides by the count. The median sorts and takes the middle value. Here they're equal because the numbers are evenly spaced, but one huge value would pull the mean up and hardly move the median.
For spread, take each value's distance from the mean: -20, -10, 0, 10, 20. Square those and average them, and you get the variance, 200. The standard deviation is its square root, about 14.14, in the same units as your data. It tells you how far a typical value sits from the mean.
Each of these has a method form too: np.sum(a) and a.sum() both give 150. Use whichever reads better.
Where a value sits
scores = np.array([72, 95, 64, 88, 95])
print(scores.argmax())
print(scores.argmin())
print(scores[scores.argmax()])
1
2
95
argmax gives the position, not the value. 95 sits at positions 1 and 4, and you get 1, because argmax returns the first one it finds.
The axis parameter
With no axis, everything collapses. A 2 by 3 array of 1 to 6 sums to 21 and its mean is 3.5. But often you want a total for each column, or for each row.
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.sum(m, axis=0))
print(np.mean(m, axis=0))
print(np.sum(m, axis=0).shape)
[5 7 9]
[2.5 3.5 4.5]
(3,)
print(np.sum(m, axis=1))
print(np.mean(m, axis=1))
print(np.sum(m, axis=1).shape)
[ 6 15]
[2. 5.]
(2,)
Axis 0 is the rows axis. NumPy travels down through the rows and they collapse, so you get one number per column, like the totals row at the bottom of a spreadsheet. Axis 1 travels across each row and gives one number per row, like a totals column on the right.
So here's the rule to remember: the axis you name is the axis that disappears. It holds in any number of dimensions:
cube = np.arange(24).reshape(2, 3, 4)
print(cube.shape)
print(cube.sum(axis=0).shape)
print(cube.sum(axis=1).shape)
print(cube.sum(axis=2).shape)
(2, 3, 4)
(3, 4)
(2, 4)
(2, 3)
You don't need to picture a cube. Just cross out that number in the shape.
keepdims keeps the axis
row_mean = m.mean(axis=1, keepdims=True)
print(row_mean.shape)
print(row_mean)
print(m - row_mean)
(2, 1)
[[2.]
[5.]]
[[-1. 0. 1.]
[-1. 0. 1.]]
With keepdims=True, the axis shrinks to size one instead of disappearing. The shape (2, 1) broadcasts across the columns, so each value is now measured from its own row's average. (See broadcasting for why that works.)
Ask for an axis that isn't there, like np.sum(m, axis=2) on a 2D array, and the traceback ends with:
numpy.exceptions.AxisError: axis 2 is out of bounds for array of dimension 2
Axes count from zero, so a 2D array only has 0 and 1. Check the shape first.
Running totals and differences
transactions = np.array([100, -20, 50, -10, 30])
growth = np.array([1.05, 1.10, 0.95, 1.20])
print(np.cumsum(transactions))
print(np.cumprod(growth).round(3))
[100 80 130 120 150]
[1.05 1.155 1.097 1.317]
Like a bank statement, cumsum keeps every step, and the last value is the plain sum. cumprod compounds the growth figures. These take an axis too: on m, np.cumsum(m, axis=1) gives [[1 3 6] [4 9 15]] and axis=0 gives [[1 2 3] [5 7 9]]. Nothing disappears this time, because a running total keeps every step.
temps = np.array([72, 75, 71, 68, 73])
print(np.diff(temps))
print(temps[-1] - temps[0])
print(np.diff(temps).sum())
[ 3 -4 -3 5]
1
1
np.diff goes the other way: each gap is the next value minus this one, so five values give four gaps. Reach for it when you care about change, not the level.
Percentiles and quantiles
data = np.array([45, 67, 89, 23, 56, 78, 90, 34])
print(np.sort(data))
print(np.percentile(data, 25))
print(np.percentile(data, 50))
print(np.percentile(data, 75))
print(np.percentile(data, [25, 50, 75]))
[23 34 45 56 67 78 89 90]
42.25
61.5
80.75
[42.25 61.5 80.75]
A percentile is the value a given percent of the data sits below. The 25th lands a quarter of the way along the sorted values, between 34 and 45, at 42.25. The 50th is the median. None of the three is in the data: NumPy works out a point between two values.
print(np.quantile(data, 0.5))
print(np.quantile(data, [0.25, 0.75]))
q1, q3 = np.percentile(data, [25, 75])
print("spread:", q3 - q1)
61.5
[42.25 80.75]
spread: 38.5
A quantile is the same idea on a 0 to 1 scale. The gap between the 25th and 75th is the interquartile range, how wide the middle half of your data is. A few extreme values won't throw it off.
Missing values
temps = np.array([21.5, np.nan, 23.0, 22.5])
print(np.mean(temps))
print(np.nanmean(temps))
print(np.nanmax(temps))
nan
22.333333333333332
23.0
One nan (not a number) spreads through the whole calculation. The nan versions skip the gap. If an answer comes out as nan, look for a missing value.
Sorting
a = np.array([30, 10, 50, 20, 40])
print(np.sort(a))
print(a)
print(np.sort(a)[::-1])
b = a.copy()
b.sort()
print(b)
[10 20 30 40 50]
[30 10 50 20 40]
[50 40 30 20 10]
[10 20 30 40 50]
np.sort returns a new array and leaves a alone. There's no largest-first option, so add [::-1]. The method b.sort() changes b itself, in place, which is why the file copies a first. With an axis, np.sort(m, axis=1) sorts each row on its own; a sort keeps every value, so the shape doesn't change.
argsort: the order, not the values
names = np.array(["Ann", "Raj", "Mia", "Leo", "Zoe"])
scores = np.array([72, 95, 64, 88, 80])
order = np.argsort(scores)
print(order)
print(names[order])
print(names[order][::-1])
[2 0 4 3 1]
['Mia' 'Ann' 'Zoe' 'Leo' 'Raj']
['Raj' 'Leo' 'Zoe' 'Ann' 'Mia']
Sort the scores alone and you lose who got what. argsort gives the positions in sorted order, and you use those same positions on names. Reverse it and you have a leaderboard. So argsort lets one array put another in order.
Counting what's there
grades = np.array(list("ABACBABC"))
print(np.unique(grades))
vals, counts = np.unique(grades, return_counts=True)
print(vals)
print(counts)
print(vals[np.argmax(counts)])
['A' 'B' 'C']
['A' 'B' 'C']
[3 3 2]
A
A and B are tied at three, and argmax returns the first. Counting with a condition is just as short:
scores = np.array([45, 67, 89, 23, 56, 78, 90, 34])
passed = scores >= 50
print(passed)
print(np.sum(passed))
print(np.count_nonzero(passed))
print(np.mean(passed))
[False True True False True True True False]
5
5
0.625
True counts as one and False as zero, so the sum of a condition is a count and the mean is a fraction: five out of eight passed.
A small analysis: five students, three subjects
import numpy as np
students = ["Alice", "Bob", "Cara", "Dan", "Eve"]
scores = np.array([
[88, 92, 79],
[75, 68, 84],
[93, 87, 91],
[62, 74, 66],
[95, 90, 88],
])
student_avg = np.mean(scores, axis=1)
subject_avg = np.mean(scores, axis=0)
print(student_avg.round(1))
print(subject_avg.round(1))
print("overall:", scores.mean().round(1))
rank = np.argsort(student_avg)[::-1]
for place, i in enumerate(rank, start=1):
avg = student_avg[i]
print(f"#{place} {students[i]} ({avg:.1f})")
[86.3 75.7 90.3 67.3 91. ]
[82.6 82.2 81.6]
overall: 82.1
#1 Eve (91.0)
#2 Cara (90.3)
#3 Alice (86.3)
#4 Bob (75.7)
#5 Dan (67.3)
Each row is a student and each column a subject. Student averages collapse the columns (axis 1), subject averages collapse the rows (axis 0), and no axis gives the overall mean. Then argsort reversed ranks them.
Recap
| Job | Functions |
|---|---|
| Many values to one | sum, prod, min, max, mean, median, var, std |
| Where it is | argmax, argmin (first match) |
| axis | The axis you name disappears; keepdims=True keeps it as size 1 |
| Every step | cumsum, cumprod, diff |
| Where values sit | percentile, quantile, nanmean and friends |
| Order and counts | sort, argsort, unique(return_counts=True), sum of a condition |
Try it yourself: in the student analysis, find the highest score in each subject. Or ask an AI tool to write it, then read every line it gives you.
Next: linear algebra with NumPy.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
