NumPy cumsum()

The numpy.cumsum() function computes the cumulative sum of elements in an array along a specified axis.

Syntax

</>
Copy
numpy.cumsum(a, axis=None, dtype=None, out=None)

Parameters

ParameterTypeDescription
aarray_likeInput array whose cumulative sum is to be computed.
axisint, optionalAxis along which the cumulative sum is computed. If None, the input is flattened before summing.
dtypedtype, optionalData type of the output array. If not specified, it defaults to the dtype of a.
outndarray, optionalOptional output array where the result is stored. Must have the same shape as expected output.

Return Value

Returns an array of the same shape as a, with each element containing the cumulative sum along the specified axis.


Examples

1. Cumulative Sum of a 1D Array

Computing the cumulative sum of a one-dimensional array.

</>
Copy
import numpy as np

# Define a 1D array
arr = np.array([1, 2, 3, 4, 5])

# Compute the cumulative sum
result = np.cumsum(arr)

# Print the result
print("Cumulative sum of the array:", result)

Output:

Cumulative sum of the array: [ 1  3  6 10 15]

2. Cumulative Sum Along an Axis

Computing the cumulative sum along a specific axis in a 2D array.

</>
Copy
import numpy as np

# Define a 2D array
arr = np.array([[1, 2, 3], 
                [4, 5, 6]])

# Compute cumulative sum along axis 0 (column-wise)
result_axis0 = np.cumsum(arr, axis=0)

# Compute cumulative sum along axis 1 (row-wise)
result_axis1 = np.cumsum(arr, axis=1)

# Print the results
print("Cumulative sum along axis 0 (columns):\n", result_axis0)
print("Cumulative sum along axis 1 (rows):\n", result_axis1)

Output:

Cumulative sum along axis 0 (columns):
[[ 1  2  3]
 [ 5  7  9]]

Cumulative sum along axis 1 (rows):
[[ 1  3  6]
 [ 4  9 15]]

3. Using the dtype Parameter

Changing the data type of the output to float while computing the cumulative sum.

</>
Copy
import numpy as np

# Define an integer array
arr = np.array([1, 2, 3, 4])

# Compute cumulative sum with dtype=float
result = np.cumsum(arr, dtype=float)

# Print the result
print("Cumulative sum with dtype float:", result)

Output:

Cumulative sum with dtype float: [ 1.  3.  6. 10.]

4. Using the out Parameter

Storing the cumulative sum result in a preallocated output array.

</>
Copy
import numpy as np

# Define an input array
arr = np.array([10, 20, 30, 40])

# Create an output array with the same shape
output_array = np.empty_like(arr)

# Compute cumulative sum and store in output_array
np.cumsum(arr, out=output_array)

# Print the result
print("Cumulative sum stored in output array:", output_array)

Output:

Cumulative sum stored in output array: [10 30 60 100]