How to Use numpy cumsum for Cumulative Sums
Use
numpy.cumsum() to get the cumulative sum of array elements along a specified axis. It returns an array where each element is the sum of all previous elements plus the current one.Syntax
The basic syntax of numpy.cumsum() is:
numpy.cumsum(a, axis=None, dtype=None, out=None)
Where:
a: Input array to compute the cumulative sum.axis: Axis along which the cumulative sum is computed. Default isNone, which flattens the array.dtype: Data type of the returned array. If not specified, it uses the input array's dtype or a default type with higher precision.out: Optional output array to store the result.
python
numpy.cumsum(a, axis=None, dtype=None, out=None)
Example
This example shows how to use numpy.cumsum() on a 1D and 2D array to get cumulative sums along different axes.
python
import numpy as np # 1D array example arr1d = np.array([1, 2, 3, 4]) cumsum_1d = np.cumsum(arr1d) # 2D array example arr2d = np.array([[1, 2, 3], [4, 5, 6]]) cumsum_2d_axis0 = np.cumsum(arr2d, axis=0) # sum down rows cumsum_2d_axis1 = np.cumsum(arr2d, axis=1) # sum across columns print('1D cumulative sum:', cumsum_1d) print('2D cumulative sum along axis 0:\n', cumsum_2d_axis0) print('2D cumulative sum along axis 1:\n', cumsum_2d_axis1)
Output
1D cumulative sum: [ 1 3 6 10]
2D cumulative sum along axis 0:
[[1 2 3]
[5 7 9]]
2D cumulative sum along axis 1:
[[ 1 3 6]
[ 4 9 15]]
Common Pitfalls
Common mistakes when using numpy.cumsum() include:
- Not specifying the
axiswhen working with multi-dimensional arrays, which causes the array to flatten and may give unexpected results. - Assuming the original array is not changed;
cumsumreturns a new array and does not modify the input. - Using integer dtype for large sums can cause overflow; specify a larger
dtypelikenp.int64if needed.
python
import numpy as np arr = np.array([[1, 2], [3, 4]]) # Wrong: forgetting axis flattens the array wrong_cumsum = np.cumsum(arr) # Right: specify axis to get cumulative sum along rows right_cumsum = np.cumsum(arr, axis=1) print('Wrong cumsum (flattened):', wrong_cumsum) print('Right cumsum (axis=1):', right_cumsum)
Output
Wrong cumsum (flattened): [ 1 3 6 10]
Right cumsum (axis=1): [[1 3]
[3 7]]
Quick Reference
Tips for using numpy.cumsum():
- Use
axis=Noneto flatten the array before summing. - Specify
axisto sum along rows (axis=1) or columns (axis=0) in 2D arrays. - Set
dtypeto avoid overflow for large sums. - The function returns a new array; original data stays unchanged.
Key Takeaways
Use numpy.cumsum() to get cumulative sums of array elements easily.
Specify the axis parameter to control the direction of summation in multi-dimensional arrays.
The function returns a new array and does not modify the original array.
Set dtype to a larger type if you expect large sums to avoid overflow.
Without axis, the array is flattened before summing.