NumPy: Aggregation Operations
Last updated: 2026-08-26
1. What You'll Learn
- ❶ Basic aggregations: sum, mean, std, var, min, max
- ❷ Axis-based aggregation: reducing along specific dimensions
- ❸ NaN-safe functions: nanmean, nansum, nanstd
- ❹ Cumulative operations: cumsum, cumprod
- ❺ Aggregation vs Python built-ins
2. Story
Alice needs to compute the average, max, and standard deviation of 10 million sensor readings. In Python, she'd write three loops — 15 seconds. In NumPy: data.mean(), data.max(), data.std() — 0.05 seconds total. "Aggregation in NumPy isn't just faster — it's a different paradigm. One function call, C-level execution, no Python loop."
3. Key Concepts
(1) Basic Aggregations
import numpy as np
a = np.array([3, 7, 1, 9, 5])
print(a.sum()) # 25
print(a.mean()) # 5.0
print(a.std()) # 2.828
print(a.var()) # 8.0
print(a.min()) # 1
print(a.max()) # 9
print(a.argmin()) # 2 (index of min)
print(a.argmax()) # 3 (index of max)
print(a.ptp()) # 8 (peak to peak: max - min)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(2) Axis-Based Aggregation
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# Sum along axis 0 (column-wise)
print(a.sum(axis=0)) # [12 15 18 21]
# Sum along axis 1 (row-wise)
print(a.sum(axis=1)) # [6 22 38]
# Global sum
print(a.sum()) # 66
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(3) NaN-Safe Functions
Real-world data often contains NaN values. Standard aggregations propagate NaN:
import numpy as np
a = np.array([1.0, 2.0, np.nan, 4.0])
print(a.mean()) # nan
print(np.nanmean(a)) # 2.333
print(np.nansum(a)) # 7.0
print(np.nanstd(a)) # 1.247
print(np.nanmin(a)) # 1.0
print(np.nanmax(a)) # 4.0
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(4) Cumulative Operations
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(np.cumsum(a)) # [1 3 6 10 15]
print(np.cumprod(a)) # [1 2 6 24 120]
▶ Example
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: Axis aggregation on 2D (Difficulty ⭐⭐)
import numpy as np
a = np.arange(12).reshape(3, 4)
print("axis=0 (column-wise):")
print(f" sum: {a.sum(axis=0)}")
print(f" mean: {a.mean(axis=0)}")
print(f" max: {a.max(axis=0)}")
print("axis=1 (row-wise):")
print(f" sum: {a.sum(axis=1)}")
print(f" mean: {a.mean(axis=1)}")
print(f" max: {a.max(axis=1)}")
▶ Example: NaN-safe aggregation (Difficulty ⭐⭐)
import numpy as np
data = np.array([1.0, 2.0, np.nan, 4.0, np.nan, 6.0])
print("Standard mean:", data.mean())
print("nanmean:", np.nanmean(data))
print("nansum:", np.nansum(data))
print("nanstd:", np.nanstd(data))
print("nanmin:", np.nanmin(data))
print("nanmax:", np.nanmax(data))
# Count non-NaN values
print("Valid count:", np.sum(~np.isnan(data)))
Output:
TEXT 📖 Display onlyStandard mean: nan nanmean: 3.25 nansum: 13.0 nanstd: 1.9202864369672785 nanmin: 1.0 nanmax: 6.0 Valid count: 4
▶ Example: Cumulative operations (Difficulty ⭐)
import numpy as np
# Running total
sales = np.array([10, 15, 7, 20, 13])
cumulative = np.cumsum(sales)
print("Daily sales:", sales)
print("Cumulative:", cumulative)
# Cumulative product
factors = np.array([1.1, 1.05, 0.98, 1.02])
growth = np.cumprod(factors)
print("Growth factors:", growth)
# 2D cumulative sum
a = np.arange(12).reshape(3, 4)
print("Row-wise cumsum:\n", np.cumsum(a, axis=1))
Output:
TEXT 📖 Display onlyDaily sales: [10 15 7 20 13] Cumulative: [10 25 32 52 65] Growth factors: [1.1 1.155 1.1319 1.154538] Row-wise cumsum: [[ 0 1 3 6] [ 4 9 15 22] [ 8 17 27 38]]
❓ FAQ
a.sum() is a method on the ndarray object; np.sum(a) is the function form. Use whichever reads better in context.np.nanmean(), np.nansum(), np.nanstd() etc. These functions skip NaN values automatically. The standard mean(), sum() propagate NaN.keepdims=True preserves the reduced dimension as size 1, making broadcasting easier. For example, a.sum(axis=1, keepdims=True) returns shape (3, 1) instead of (3,).📖 Summary
- Basic aggregations: sum, mean, std, var, min, max, argmin, argmax, ptp
- Axis parameter controls which dimension to reduce;
keepdimspreserves dimensions - NaN-safe functions: nanmean, nansum, nanstd, nanmin, nanmax
- Cumulative: cumsum, cumprod for running totals and products
📝 Exercises
-
Beginner (Difficulty ⭐): Create a 4x4 array of random integers 0-100. Compute the sum, mean, min, max, and std of the entire array. Then compute the same statistics along each axis.
-
Intermediate (Difficulty ⭐⭐): Create an array with NaN values. Compute the mean with and without NaN-safe functions. Explain the difference.
-
Advanced (Difficulty ⭐⭐⭐): Generate a 10,000x5 array of random data. Compute the z-score (standardize) for each column using axis-based mean and std. Verify that each column has mean ≈ 0 and std ≈ 1.