w3resource

NumPy: Calculate cumulative sum of the elements along a given axis


27. Cumulative Sum and Row/Column Sums

Write a NumPy program to calculate cumulative sum of the elements along a given axis, sum over rows for each of the 3 columns and sum over columns for each of the 2 rows of a given 3x3 array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

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

# Displaying the original array
print("Original array: ")
print(x)

# Calculating the cumulative sum of all elements in the array
print("Cumulative sum of the elements along a given axis:")
r = np.cumsum(x)
print(r)

# Calculating the cumulative sum over rows for each of the 3 columns
print("\nSum over rows for each of the 3 columns:")
r = np.cumsum(x, axis=0)
print(r)

# Calculating the cumulative sum over columns for each of the 2 rows
print("\nSum over columns for each of the 2 rows:")
r = np.cumsum(x, axis=1)
print(r) 

Sample Output:

Original array: 
[[1 2 3]
 [4 5 6]]
Cumulative sum of the elements along a given axis:
[ 1  3  6 10 15 21]

Sum over rows for each of the 3 columns:
[[1 2 3]
 [5 7 9]]

Sum over columns for each of the 2 rows:
[[ 1  3  6]
 [ 4  9 15]]

Explanation:

x = np.array([[1,2,3], [4,5,6]]) – x is a two-dimensional NumPy array with shape (2, 3). The first row of the array is [1, 2, 3] and the second row is [4, 5, 6].

np.cumsum(x): This line computes the cumulative sum of all elements in the flattened array and returns [ 1 3 6 10 15 21]

np.cumsum(x, axis=0): This line computes the cumulative sum of elements along the rows of the array x and returns [[1, 2, 3], [5, 7, 9]]

np.cumsum(x, axis=1): This line computes the cumulative sum of elements along the columns of the array x and returns [[ 1, 3, 6], [ 4, 9, 15]].


For more Practice: Solve these Related Problems:

  • Implement a function that computes the cumulative sum of a 2D array using np.cumsum and reshapes the result to the original array dimensions.
  • Test the function to calculate both the row-wise and column-wise cumulative sums and verify against manual totals.
  • Create a solution that returns the cumulative sum along with overall row and column sums as separate arrays.
  • Apply the function on a transposed array and compare the results with the original cumulative sums for consistency.

Go to:


PREV : Rounding, Floor, Ceil, and Truncation
NEXT : Cumulative Product and Row/Column Products

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.