.cumsum()
Published Apr 2, 2025
Contribute to Docs
In NumPy, the .cumsum()
function computes the cumulative sum of elements in an array along a specified axis.
Syntax
numpy.cumsum(a, axis=None, dtype=None, out=None)
Parameters:
a
: The array of elements to calculate the cumulative sum of.axis
(Optional): Axis along which the cumulative sum is computed. Default isNone
, meaning the sum is computed over the flattened array.dtype
(Optional): The datatype of the returned array. IfNone
, it defaults to the input array’sdtype
.out
(Optional): Alternative output array in which to place the result.
Return value:
Returns a new NumPy array containing the cumulative sum of elements along the specified axis.
Example
This example demonstrates how to compute the cumulative sum of a NumPy array using .cumsum()
:
import numpy as np# Create an arrayarray = np.array([1, 2, 3, 4, 5])# Compute the cumulative sum of the arraycumulative_sum = np.cumsum(array)# Print out the original arrayprint("Original Array:", array)# Print out the returned arrayprint("Cumulative Sum:", cumulative_sum)
This produces the following output:
Original Array: [1 2 3 4 5]Cumulative Sum: [ 1 3 6 10 15]
Codebyte Example
Run the following codebyte example to better understand the .cumsum()
function:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours