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:
- 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
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:
result:
[[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:
result:
[[ 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!!