NumPy: Calculate cumulative sum of the elements along a given axis
NumPy Mathematics: Exercise-27 with Solution
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]].
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-math-exercise-27.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics