0
0
NumPydata~10 mins

np.cumsum() for cumulative sum in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - np.cumsum() for cumulative sum
Start with array
Initialize sum = 0
Take next element
Add element to sum
Store sum in output array
More elements?
YesTake next element
No
Return cumulative sum array
np.cumsum() takes an array and adds elements one by one, storing the running total at each step, returning an array of these sums.
Execution Sample
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
cum_sum = np.cumsum(arr)
print(cum_sum)
This code calculates the cumulative sum of the array [1, 2, 3, 4].
Execution Table
StepCurrent ElementRunning Sum BeforeRunning Sum AfterOutput Array So Far
1101[1]
2213[1, 3]
3336[1, 3, 6]
44610[1, 3, 6, 10]
💡 All elements processed; cumulative sum array complete.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
running_sum01361010
output_array[][1][1, 3][1, 3, 6][1, 3, 6, 10][1, 3, 6, 10]
Key Moments - 3 Insights
Why does the first element of the output equal the first element of the input?
Because the running sum starts at zero, adding the first element gives the first cumulative sum, as shown in step 1 of the execution_table.
Does np.cumsum() change the original array?
No, np.cumsum() creates a new array with cumulative sums, leaving the original array unchanged, as seen by the separate output_array in variable_tracker.
What happens if the input array is empty?
The output will also be an empty array because there are no elements to sum, so the loop in the concept_flow never runs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the running sum after processing the third element?
A3
B6
C10
D1
💡 Hint
Check the 'Running Sum After' column at step 3 in the execution_table.
At which step does the output array first contain [1, 3]?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Output Array So Far' column in the execution_table.
If the input array was [2, 2, 2], what would be the final cumulative sum?
A[2, 4, 6]
B[2, 2, 2]
C[1, 3, 6]
D[0, 2, 4]
💡 Hint
Cumulative sum adds each element to the sum of all previous elements, as shown in variable_tracker.
Concept Snapshot
np.cumsum(array) returns a new array with cumulative sums.
Starts from zero, adds each element in order.
Output length equals input length.
Original array stays unchanged.
Useful for running totals or progressive sums.
Full Transcript
np.cumsum() calculates the cumulative sum of an array by adding each element to the sum of all previous elements. Starting from zero, it processes each element one by one, updating the running sum and storing it in a new output array. The original array remains unchanged. For example, given [1, 2, 3, 4], the cumulative sums are [1, 3, 6, 10]. This process is useful when you want to track totals that build up over time or steps.