• Post author:
• Post category:NumPy / Python

In Python, NumPy is a powerful library for numerical and mathematical operations. The numpy.cumsum() function is used to compute the cumulative sum of array elements along a specified axis. If the axis parameter is provided, it calculates the cumulative sum along the specified axis. In this article, I will explain syntax and how to use the numpy.cumsum() function which returns a cumulative sum of the input array.

## 1. Quick Examples of NumPy cumsum() Function

If you are in a hurry, below are some quick examples of how to use cumsum() function in NumPy.

# Quick examples of numpy cumsum() function

import numpy as np

# Example 1: Get the cumsum of the integer
arr = 12
cumulative_sum = np.cumsum(arr)

# Example 2: Compute a cumulative sum
arr = np.array([2, 7, 5, 8, 9, 4])
cumulative_sum = np.cumsum(arr)

# Example 3: Get the cumulative sum of numpy array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6],[12, 8, 14, 11]])
cumulative_sum = np.cumsum(arr)

# Example 4: Get the cumulative sum over columns (axis=0)
cumulative_sum = np.cumsum(arr, axis=0)

# Example 5: Get the cumulative sum over rows (axis=1)
cumulative_sum = np.cumsum(arr, axis=1)

# Example 6: Get the cumulative sum of an array
# Along with specified datatype
cumulative_sum = np.cumsum(arr, dtype = float)

# Example 7: Get cumulative sum over columns
# For each of 3 rows along with datatype
cumulative_sum = np.cumsum(arr, axis=1, dtype=float)

## 2. Syntax of cumsum()

Following is the syntax of the cumsum() function.

# Syntax of numpy.cumsum()
numpy.cumsum(arr, axis=None, dtype=None, out=None)

### 2.1 Parameters of cumsum()

• arr – The input array containing numbers whose cumulative sum is desired. If arr is not an array, a conversion is attempted.
• axis – The axis along which the cumulative sum is computed. The default is to compute the sum of the flattened array.
• dtype – Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of arr, unless arr has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.
• out – It is a ndarray and an optional. A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly allocated array is returned.

### 2.2 Return Value of cumsum()

It returns a new array holding the result unless out is specified.

## 3. Usage of NumPy cumsum() Function

Use numpy.cumsum() function to compute the cumulative sum of array elements over a given axis. The process of formation of the cumulative sum of an array is, it keeps the first element as is, the second element is the sum of the first element and the second element, and the third element is the sum of the first, second, and the third element, and so on.

When you use a single scalar value to cumsum(), it returns the same value. If you want to find the cumulative sum of a scalar integer, you need to create an array-like object first. For instance, np.array([12]) creates a 1-dimensional NumPy array with a single element, and then np.cumsum() is applied to this array, resulting in the cumulative sum [12].

# Import numpy
import numpy as np

# Get the cumsum of integer
arr = 12
cumulative_sum = np.cumsum(arr)
print("Cumulative sum of integer:", cumulative_sum)

Yields below output.

## 4. Get the Cumulative sum of a 1-D NumPy Array

Let’s use a NumPy 1-dimensional array and calculate the cumulative sum, to do so first create a NumPy array using numpy.array() function and pass the array as an argument to the function. This returns the array with cumulative sum values.

To get the cumulative sum of a 1-dimensional NumPy array, you can use the numpy.cumsum() function. In this program, the numpy.cumsum() function calculates the cumulative sum of the elements in the input array [2, 7, 5, 8, 9, 4], resulting in the output array [ 2 9 14 22 31 35].

# Creating an 1D input array
arr = np.array([2, 7, 5, 8, 9, 4])
print("Original array:",arr)

# Compute cumulative sum
cumulative_sum = np.cumsum(arr)
print("Cumulative sum array:", cumulative_sum)

Yields below output.

## 5. Get the Cumulative sum of a 2-D NumPy Array

When you use numpy.cumsum() to compute the cumulative sum of the 2-D NumPy array, it will return the cumulated sum of the flattened array.

# Create 2D array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6],[12, 8, 14, 11]])
print("Original array:\n",arr)

# Get the cumulative sum of numpy array
cumulative_sum = np.cumsum(arr)
print("Cumulative sum of numpy 2D array:\n", cumulative_sum)

# Output:
# Original array:
#  [[ 5  8  3  7]
#  [ 9  4  2  6]
#  [12  8 14 11]]
# Cumulative sum of numpy 2D array:
#  [ 5 13 16 23 32 36 38 44 56 64 78 89]

## 6. Get the Cumulative sum Over Columns of a 2-D Array

To calculate the cumulative sum over columns of a 2-dimensional NumPy array, you can use the numpy.cumsum() function with axis=0. For instance, np.cumsum(arr, axis=0) calculates the cumulative sum over columns of the 2-dimensional NumPy array arr. The resulting cumulative_sum array contains the cumulative sum for each column of the original array.

# Create 2D array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6],[12, 8, 14, 11]])
print("Original array:\n",arr)

# Get the cumulative sum over columns (axis=0)
cumulative_sum = np.cumsum(arr, axis=0)
print("Cumulative sum over columns:\n",cumulative_sum)

# Output:
# Original array:
#  [[ 5  8  3  7]
#  [ 9  4  2  6]
#  [12  8 14 11]]
# Cumulative sum over columns:
#  [[ 5  8  3  7]
#  [14 12  5 13]
#  [26 20 19 24]]

## 7. Get the Cumulative sum Over Rows of a 2-D Array

To calculate the cumulative sum over rows of a 2-dimensional NumPy array, you can use the numpy.cumsum() function with axis=1. For example, np.cumsum(arr, axis=1) calculates the cumulative sum over rows of the 2-dimensional NumPy array arr. The resulting cumulative_sum array contains the cumulative sum for each row of the original array.

# Get the cumulative sum over rows (axis=1)
cumulative_sum = np.cumsum(arr, axis=1)
print("Cumulative sum over rows:\n",cumulative_sum)

# Output:
# Original array:
#  [[ 5  8  3  7]
#  [ 9  4  2  6]
#  [12  8 14 11]]
# Cumulative sum over rows:
#  [[ 5 13 16 23]
#  [ 9 13 15 21]
#  [12 20 34 45]]

## 8. Get the Cumulative sum of a 2-D Array along Data Type

If you want a cumulative sum output array in a specific data type use the dtype argument. For example, the elements of the cumulative_sum array are of data type float because you specified dtype=float in the np.cumsum() function. The cumulative sum is calculated for each element of the flattened array using the specified data type.

# Create 2D array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6],[12, 8, 14, 11]])

# Get the cumulative sum of an array
# Along with specified datatype
cumulative_sum = np.cumsum(arr, dtype = float)
print("Cumulative sum specified datatype:\n",cumulative_sum)

# Output:
# Cumulative sum specified datatype:
#  [ 5. 13. 16. 23. 32. 36. 38. 44. 56. 64. 78. 89.]

Alternatively, the np.cumsum(arr,axis=1,dtype=float) calculates the cumulative sum over rows, and the resulting cumulative_sum array contains the cumulative sum for each element in the rows of the original 2-dimensional NumPy array arr, with the data type specified as float.

# Create 2D array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6],[12, 8, 14, 11]])

# Get cumulative sum over columns
# For each of 3 rows along with datatype
cumulative_sum = np.cumsum(arr, axis=1, dtype=float)
print("Cumulative sum over rows:\n",cumulative_sum)

# Output:
# Cumulative sum over rows:
#  [[ 5. 13. 16. 23.]
#  [ 9. 13. 15. 21.]
#  [12. 20. 34. 45.]]

What does the numpy.cumsum() function do?

The numpy.cumsum() function in NumPy calculates the cumulative sum of array elements along a specified axis or the flattened array. For a 1-dimensional array, it computes the cumulative sum of elements. For multi-dimensional arrays, it can calculate the cumulative sum along a specified axis.

How can I calculate the cumulative sum of a 1-dimensional NumPy array?

To calculate the cumulative sum of a 1-dimensional NumPy array, you can use the numpy.cumsum().

How can I calculate the cumulative sum of a 2-dimensional NumPy array along rows?

To calculate the cumulative sum of a 2-dimensional NumPy array along rows (or axis 1), you can use the numpy.cumsum() function with the axis parameter set to 1.

How can I calculate the cumulative sum of a 2-dimensional NumPy array along columns?

To calculate the cumulative sum of a 2-dimensional NumPy array along columns (or axis 0), you can use the numpy.cumsum() function with the axis parameter set to 0.

Can I specify a data type for the output of numpy.cumsum() function?

You can specify a data type for the output of the numpy.cumsum() function using the dtype parameter. When you specify a data type, the cumulative sum will be computed with that specific data type. For example, np.cumsum(arr, dtype=float) will calculate the cumulative sum with float elements.

What happens if I use numpy.cumsum() with a scalar value?

If you use a scalar value directly with np.cumsum(), it will raise a TypeError because the function expects an array-like object as input.

## Conclusion

In this article, I have explained how to use NumPy.cumsum() function and using this how to compute the cumulative sum of NumPy array along with specified axis and specified datatype.

Happy Learning!!