How to Use the Numpy cumsum() Function in Python

09/11/2021

Contents

In this article, you will learn how to use the Numpy cumsum() function in Python.

Numpy cumsum() Function

The numpy cumsum() function is used to compute the cumulative sum of elements in a numpy array. Here’s how to use it:

Import the numpy library:
import numpy as np
Create a numpy array:
arr = np.array([1, 2, 3, 4, 5])
Use the cumsum() function on the array:
cumulative_sum = np.cumsum(arr)
Print the cumulative sum:
cumulative_sum = np.cumsum(arr)

The output will be:

[ 1  3  6 10 15]

The first element in the output is the same as the first element in the input array. The second element is the sum of the first and second elements in the input array, and so on. The last element in the output is the sum of all the elements in the input array.

 

Here’s some additional information about the numpy cumsum() function:

  • The cumsum() function can be applied to multi-dimensional numpy arrays, along a specified axis. In this case, the function returns an array of the same shape as the input array, with cumulative sums computed along the specified axis.
  • The function takes a second argument, axis, which specifies the axis along which to compute the cumulative sum. By default, the function computes the cumulative sum over a flattened input array.
  • The cumsum() function returns a new numpy array, so the original input array is not modified.
  • The numpy cumsum() function can be used in various applications, such as computing the running total of sales, tracking inventory levels, or analyzing financial data.
  • It’s important to note that the numpy cumsum() function computes the cumulative sum of the elements in an array using a recursive algorithm, which can result in numerical errors for large arrays with very small values. In these cases, it’s recommended to use the numpy cumsum() function with floating-point numbers.