Last Updated : 04 Dec, 2024
numpy.cumsum()
function is used to compute the cumulative sum of elements in an array. Cumulative sum refers to a sequence where each element is the sum of all previous elements plus itself.
For example, given an array [1, 2, 3, 4, 5], the
cumulative sum would be [1, 3, 6, 10, 15].
Let's implement this as well:
import numpy as np
array = np.array([1, 2, 3, 4, 5])
cumulative_sum = np.cumsum(array)
print("Original array:", array)
print("Cumulative sum:", cumulative_sum)
Output:
numpy.cumsum() in PythonThe numpy.cumsum()
function computes the cumulative sum of array elements along a specified axis or across the entire flattened array. This function can handle both one-dimensional and multi-dimensional arrays, providing flexibility in how cumulative sums are calculated.
Syntax for numpy.cumsum()
is:
1. Cumulative Sum of a One-Dimensional Arraynumpy.cumsum(array, axis=None, dtype=None, out=None)
where,
- array: The input array containing numbers whose cumulative sum is desired.
- axis: (Optional) The axis along which the cumulative sum is computed. If not specified, the array is flattened.
- dtype: (Optional) The data type of the returned array.
- out: (Optional) An alternative output array to place the result
To calculate the cumulative sum of a one-dimensional array:
Python
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
cumulative_sum = np.cumsum(array1)
print(cumulative_sum)
# Output: [ 1 3 6 10 15]
This example demonstrates how each element in the resulting array represents the sum of all preceding elements including itself
2. Cumulative Sum of a Two-Dimensional ArrayFor two-dimensional arrays, you can specify an axis:
Python
import numpy as np
array2 = np.array([[1, 2], [3, 4]])
cumulative_sum_flattened = np.cumsum(array2)
cumulative_sum_axis0 = np.cumsum(array2, axis=0)
cumulative_sum_axis1 = np.cumsum(array2, axis=1)
print(cumulative_sum_flattened)
print(cumulative_sum_axis0)
print(cumulative_sum_axis1)
[ 1 3 6 10] [[1 2] [4 6]] [[1 3] [3 7]]
dtype
to Specify Data Type in NumPy cumsum
The dtype
parameter allows you to specify the data type of the output:
import numpy as np
array3 = np.array([1, 2, 3])
cumulative_sum_float = np.cumsum(array3, dtype=float)
print(cumulative_sum_float)
# Output: [1.0 3.0 6.0]
This ensures that the resulting cumulative sums are stored as floats.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4