Last modified: Oct 21, 2024 By Alexander Williams

Understanding Python numpy.cumsum()

The numpy.cumsum() function in Python is used to calculate the cumulative sum of elements in an array. It is an essential tool for performing cumulative calculations with arrays in NumPy.

Prerequisites

Before using numpy.cumsum(), ensure that NumPy is installed. If not, check our guide on How to Install NumPy in Python.

Syntax of numpy.cumsum()

The syntax of numpy.cumsum() is simple:


import numpy as np
np.cumsum(a, axis=None)

In this syntax, a is the input array, and axis specifies the axis along which the cumulative sum is computed. By default, axis=None flattens the array before summing.

Examples of numpy.cumsum()

Example 1: Using numpy.cumsum() on a 1D Array

Here’s how to use numpy.cumsum() with a 1D array:


import numpy as np

arr = np.array([1, 2, 3, 4])
cumsum_arr = np.cumsum(arr)
print(cumsum_arr)


[ 1  3  6 10]

This example calculates the cumulative sum of a 1D array, where each element is the sum of the current element and all previous elements.

Example 2: Applying numpy.cumsum() to a 2D Array

For 2D arrays, you can use the axis parameter:


import numpy as np

arr = np.array([[1, 2], [3, 4]])
cumsum_arr = np.cumsum(arr, axis=0)
print(cumsum_arr)


[[1 2]
 [4 6]]

Here, the cumulative sum is calculated along axis=0, which means summing along the rows.

Example 3: Using numpy.cumsum() with numpy.arange()

Let's see how numpy.cumsum() can be used with numpy.arange():


import numpy as np

arr = np.arange(1, 6)
cumsum_arr = np.cumsum(arr)
print(cumsum_arr)


[ 1  3  6 10 15]

This example calculates the cumulative sum of values generated by numpy.arange().

Applications of numpy.cumsum()

The numpy.cumsum() function is useful for calculating cumulative sums, which are often required in data analysis, financial computations, and time series analysis. It helps in understanding trends and patterns over a period of time.

For detailed documentation, visit the official numpy.cumsum() documentation.

Conclusion

The numpy.cumsum() function is a valuable tool for calculating cumulative sums in arrays. It is widely used in data analysis and statistical calculations, making it a must-know for anyone working with NumPy in Python.

If you found this helpful, check out our articles on Understanding Python numpy.zeros() and Understanding Python numpy.linspace().