Let us explore.
Function Syntax
The function syntax is as shown below:
Function Parameters
The function returns the parameters as shown:
- a – refers to the input array.
- axis – along which axis the cumulative sum is performed.
- dtype – specifies the data type of the output.
- 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 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:
Example #2
The following example shows how to use the cumsum() function along the zero axis.
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:
print(f"result: {np.cumsum(arr, axis=1)}")
The output array is as shown:
[[ 1 3 6]
[ 4 9 15]]
Conclusion
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!!