Aggregation Functions
Compute sum, mean, min, max, and standard deviation across an entire array or along a specific axis.
Aggregation Functions is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Aggregation?
Aggregation boils an array down to a few summary values, like a total or an average. NumPy's built-in functions do this in fast C, no loops needed.
import numpy as np
a = np.array([3, 7, 2, 9, 1, 6])
print('sum:', a.sum()) # 28
print('mean:', a.mean()) # 4.666...
print('max:', a.max()) # 9sum() and cumsum()
Use a.sum() for the total of every element, and np.cumsum for a running total — each spot holds the sum of everything up to it.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a.sum()) # 15
print(np.cumsum(a)) # [ 1 3 6 10 15]mean() and std()
a.mean() gives the average and a.std() the standard deviation. By default std divides by N; pass ddof=1 when your data is a sample.
import numpy as np
a = np.array([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
print('mean:', a.mean()) # 5.0
print('std (pop):', a.std()) # 2.0
print('std (sample):', a.std(ddof=1)) # 2.138...min() and max() with argmin/argmax
a.min() and a.max() give the smallest and largest values. Want their positions instead? argmin and argmax return the index of each.
import numpy as np
a = np.array([3, 7, 2, 9, 1, 6])
print('min:', a.min(), 'at index', a.argmin()) # 1 at 4
print('max:', a.max(), 'at index', a.argmax()) # 9 at 3Aggregating Along an Axis
The axis argument picks which dimension to collapse: axis=0 gives one value per column, axis=1 one per row. Leave it off and you reduce the whole array.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.sum(axis=0)) # [5 7 9] -- column sums
print(m.sum(axis=1)) # [ 6 15] -- row sums
print(m.mean(axis=0)) # [2.5 3.5 4.5]keepdims=True for Shape Preservation
Aggregating along an axis drops that dimension. Add keepdims=True to keep it as size 1 — essential when you want the result to broadcast back later.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
row_sums = m.sum(axis=1, keepdims=True)
print(row_sums.shape) # (2, 1)
normed = m / row_sums
print(normed.round(3))
# [[0.167 0.333 0.5 ]
# [0.267 0.333 0.4 ]]NaN-Safe Aggregations
One NaN makes a normal sum or mean return NaN. The NaN-safe versions — np.nansum, np.nanmean, and friends — simply skip the missing values.
import numpy as np
a = np.array([1.0, np.nan, 3.0, np.nan, 5.0])
print(a.sum()) # nan
print(np.nansum(a)) # 9.0
print(np.nanmean(a)) # 3.0
print(np.nanmax(a)) # 5.0np.median and np.percentile
np.median gives the middle value and shrugs off outliers far better than the mean. np.percentile finds the value below which a given percent of data sits.
import numpy as np
a = np.array([1, 2, 3, 4, 100]) # outlier at 100
print('mean:', a.mean()) # 22.0 -- skewed
print('median:', np.median(a)) # 3.0 -- robust
print(np.percentile(a, [25, 50, 75])) # [ 2. 3. 4.]np.any() and np.all()
np.any returns True if at least one element passes a condition; np.all returns True only if every element does. Both can check per row or column.
import numpy as np
a = np.array([1, -2, 3, -4])
print(np.any(a < 0)) # True (some are negative)
print(np.all(a > 0)) # False (not all are positive)
# Row-wise check on 2D
m = np.array([[1, 2], [-1, 3]])
print(np.all(m > 0, axis=1)) # [ True False]np.count_nonzero()
np.count_nonzero counts how many elements aren't zero — or how many are True. Pass it a condition like a > 5 to count matches cleanly.
import numpy as np
a = np.array([3, 0, 7, 0, 2, 0])
print(np.count_nonzero(a)) # 3
print(np.count_nonzero(a > 2)) # 2 (elements 3 and 7)
m = np.array([[0, 1], [1, 1]])
print(np.count_nonzero(m, axis=0)) # [1 2]np.unique() for Distinct Values
np.unique returns the sorted distinct values. Add return_counts=True and you also get how often each appears — an instant frequency table.
import numpy as np
a = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])
uniq, counts = np.unique(a, return_counts=True)
print(uniq) # [1 2 3 4 5 6 9]
print(counts) # [2 1 2 1 2 1 1]Quick Check
Test your understanding of NumPy aggregation functions from this lesson.
Lesson Recap
Great job! NumPy aggregations summarise arrays in fast C, the axis argument picks what to collapse, and NaN-safe versions skip missing values. Next: broadcasting.
Frequently asked questions
Is the “Aggregation Functions” lesson free?
Yes — the full text of “Aggregation Functions” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Aggregation Functions”?
Compute sum, mean, min, max, and standard deviation across an entire array or along a specific axis. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Aggregation Functions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Universal Functions (ufuncs)
- Aggregation Functions
- Broadcasting Rules
- Boolean Masking and Fancy Indexing