NumPy np.cumsum()

The cumsum() function in NumPy allows you to calculate the cumulative sum of elements along a given axis.

Let us explore.

Function Syntax

The function syntax is as shown below:

numpy.cumsum(a, axis=None, dtype=None, out=None)

Function Parameters

The function returns the parameters as shown:

  1. a – refers to the input array.
  2. axis – along which axis the cumulative sum is performed.
  3. dtype – specifies the data type of the output.
  4. out – specifies the output array to store the result.

Function Return Value

The function returns a new array with the cumulative sum of the input array elements.

Example #1

The code below shows how to calculate the cumulative sum of a two-dimensional array along the None axis.

# import numpy
import numpy as np
arr = np.array([[1,2,3], [4,5,6]])
print(f"result: {np.cumsum(arr, axis=None)}")

The code above should flatten the array and an array holding the cumulative sum of the elements.

An example output is as shown:

result: [ 1  3  6 10 15 21]

Example #2

The following example shows how to use the cumsum() function along the zero axis.

arr = np.array([[1,2,3], [4,5,6]])
print(f"result: {np.cumsum(arr, axis=0)}")

This should return:

[[1 2 3]
 [5 7 9]]

Example #3

Along the axis=1, the function returns the result as:

arr = np.array([[1,2,3], [4,5,6]])
print(f"result: {np.cumsum(arr, axis=1)}")

The output array is as shown:

[[ 1  3  6]
 [ 4  9 15]]


Using this article, you learned how to calculate the cumulative sum of elements along a given axis in an input array using the cumsum() function. Feel free to explore the docs for more.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list