w3resource

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


28. Cumulative Product and Row/Column Products

Write a NumPy program to calculate cumulative product of the elements along a given axis, sum over rows for each of the 3 columns and product 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 product of all elements in the array
print("Cumulative product of the elements along a given axis:")
r = np.cumprod(x)
print(r)

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

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

Sample Output:

Original array: 
[[1 2 3]
 [4 5 6]]
Cumulative product  of the elements along a given axis:
[  1   2   6  24 120 720]

Product over rows for each of the 3 columns:
[[ 1  2  3]
 [ 4 10 18]]

Product  over columns for each of the 2 rows:
[[  1   2   6]
 [  4  20 120]]

Explanation:

In the above exercise –

x = np.array([[1,2,3], [4,5,6]]) – This line creates a 2D NumPy array x. The array has two rows and three columns.

r = np.cumprod(x) – The np.cumprod() function is then called on x with no axis specified, resulting in the cumulative product of all elements in the array. The resulting array is assigned to r.

r = np.cumprod(x,axis=0) – The np.cumprod() function is called with axis=0. This computes the cumulative product of each column, resulting in an array of the same shape as x. The resulting array is assigned to r.

r = np.cumprod(x,axis=1) – Finally, the np.cumprod() function is called with axis=1. This computes the cumulative product of each row, resulting in an array of the same shape as x. The resulting array is assigned to r.


For more Practice: Solve these Related Problems:

  • Implement a function that computes the cumulative product of elements in a 2D array using np.cumprod and reshapes the output.
  • Test the function to compute row-wise and column-wise products and verify the results with iterative multiplication.
  • Create a solution that returns both cumulative product and final product sums over specified axes.
  • Compare the np.cumprod output with a manual multiplication loop for a small matrix to ensure accuracy.

Go to:


PREV : Cumulative Sum and Row/Column Sums
NEXT : Element-wise Difference of Neighboring Elements

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.