Python | Numpy matrix.cumprod()

Python | Numpy matrix.cumprod()

The cumprod() function in NumPy computes the cumulative product of elements along a given axis. When applied to a matrix or a 2D array, you can choose to compute the cumulative product along rows or columns.

Here's a brief explanation followed by an example:

  • By default, cumprod() will treat the matrix as a flat array (flattened using ravel), and compute the cumulative product of all elements.
  • If axis=0, the cumulative product is computed for each column, and the result will have the same number of columns as the original matrix.
  • If axis=1, the cumulative product is computed for each row.

Example:

import numpy as np # Create a 3x3 matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Cumulative product treating the matrix as a flat array print(np.cumprod(matrix)) # Output: [1 2 6 24 120 720 5040 40320 362880] # Cumulative product along columns print(np.cumprod(matrix, axis=0)) # Output: # [[ 1 2 3] # [ 4 10 18] # [ 28 80 162]] # Cumulative product along rows print(np.cumprod(matrix, axis=1)) # Output: # [[ 1 2 6] # [ 4 20 120] # [ 7 56 504]] 

In the example:

  • The default behavior treats the matrix as a flat array and computes the cumulative product of all elements.
  • When axis=0, it computes the cumulative product down each column.
  • When axis=1, it computes the cumulative product across each row.

More Tags

pkcs#12 botframework pentaho-spoon spring-integration tcplistener mustache mailto spring-el html.dropdownlistfor controllers

More Programming Guides

Other Guides

More Programming Examples