NumPy: Aggregation Operations

Last updated: 2026-08-26

1. What You'll Learn



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

PYTHON
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)
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.

(2) Axis-Based Aggregation

PYTHON
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
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.

(3) NaN-Safe Functions

Real-world data often contains NaN values. Standard aggregations propagate NaN:

PYTHON
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
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.

(4) Cumulative Operations

PYTHON
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

TEXT 📖 Display only
> **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 ⭐⭐)

PYTHON
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 ⭐⭐)

PYTHON
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 only
Standard mean: nan
nanmean: 3.25
nansum: 13.0
nanstd: 1.9202864369672785
nanmin: 1.0
nanmax: 6.0
Valid count: 4

▶ Example: Cumulative operations (Difficulty ⭐)

PYTHON
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 only
Daily 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

Q What's the difference between a.sum() and np.sum(a)?
A No difference — they're the same method. a.sum() is a method on the ndarray object; np.sum(a) is the function form. Use whichever reads better in context.
Q How do I handle NaN values in aggregation?
A Use np.nanmean(), np.nansum(), np.nanstd() etc. These functions skip NaN values automatically. The standard mean(), sum() propagate NaN.
Q What's keepdims?
A 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



📝 Exercises

  1. 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.

  2. Intermediate (Difficulty ⭐⭐): Create an array with NaN values. Compute the mean with and without NaN-safe functions. Explain the difference.

  3. 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.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏