/Curriculum/Core NumPyStatistics & Reductions

18. Cumulative FunctionsIntermediate

Calculate running totals and products with np.cumsum() and np.cumprod().

10 mins

Concept Overview

Cumulative functions compute running totals where each element in the output array is the progressive accumulation of all preceding elements up to that position.

Hardware Mental Model

Cumulative sum is like watching your savings bank account balance grow after each monthly paycheck deposit.

Key Concepts (1)Click snippet to load in editor

`np.cumsum([a, b, c])` outputs `[a, a+b, a+b+c]`. `np.cumprod([a, b, c])` outputs `[a, a*b, a*b*c]`.

running_sum = np.cumsum(arr)

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:res = arr.cumsum # Missing parentheses
✓ Correct:res = arr.cumsum()

cumsum is a function that must be called with parentheses `()`, optionally passing `axis`.

Pro Tip: Call `arr.cumsum(axis=0)` to compute running column totals down a matrix.

📌 Quick Revision

Core takeaway points from this topic
`np.cumsum()`: Progressive cumulative running sum.
`np.cumprod()`: Progressive cumulative running product.
Useful for calculating financial balances, running time, and cumulative probability densities.
Editor: 18. Cumulative Functions
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Compute Running Cumulative Sum

Create `arr = np.array([1, 2, 3, 4])`, compute its cumulative sum using `np.cumsum(arr)`, and print.

Expected Output Target:[ 1 3 6 10]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state