w3resource

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

NumPy Mathematics: Exercise-28 with Solution

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.

Python-Numpy Code Editor:

Previous: 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.

Next: Write a NumPy program to calculate the difference between neighboring elements, element-wise of a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-28.php