0
0
NumPydata~5 mins

np.cumsum() for cumulative sum in NumPy

Choose your learning style9 modes available
Introduction

We use np.cumsum() to find the running total of numbers in a list or array. It helps us see how values add up step by step.

Tracking total sales over days to see how revenue grows.
Calculating total distance traveled after each segment in a trip.
Finding cumulative scores in a game to check progress.
Summing daily calories consumed to monitor diet.
Adding up rainfall amounts over time to study weather patterns.
Syntax
NumPy
numpy.cumsum(a, axis=None, dtype=None, out=None)

# a: input array
# axis: axis along which to sum (default sums flattened array)
# dtype: data type of output
# out: optional output array to store result

The function returns an array of the same shape as input with cumulative sums.

If axis is not given, it sums over the flattened array.

Examples
Simple 1D array cumulative sum: adds values step by step.
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
cum_sum = np.cumsum(arr)
print(cum_sum)
Cumulative sum along rows (axis 0) in 2D array.
NumPy
arr2d = np.array([[1, 2], [3, 4]])
cum_sum_axis0 = np.cumsum(arr2d, axis=0)
print(cum_sum_axis0)
Cumulative sum along columns (axis 1) in 2D array.
NumPy
cum_sum_axis1 = np.cumsum(arr2d, axis=1)
print(cum_sum_axis1)
Sample Program

This program shows daily sales and their running total using np.cumsum().

NumPy
import numpy as np

# Example: daily sales
sales = np.array([100, 150, 200, 250])

# Calculate cumulative sales
cumulative_sales = np.cumsum(sales)

print("Daily sales:", sales)
print("Cumulative sales:", cumulative_sales)
OutputSuccess
Important Notes

Use axis carefully to get cumulative sums along the right direction in multi-dimensional arrays.

The output array has the same shape as the input array.

Summary

np.cumsum() calculates running totals step by step.

Works on 1D and multi-dimensional arrays.

Useful for tracking totals over time or sequence.