What is the numpy.cumprod() function in NumPy?

Overview

The numpy.cumprod() function in NumPy computes the cumulative product of the elements in a given input array over a given axis.

Syntax

numpy.cumprod(a, axis=None, dtype=None, out=None)

Parameter values

The numpy.cumprod() function takes the following parameter values:

  • a (required): This is the input array that contains numbers to be computed.
  • axis (optional): This is the axis along which the product is determined.
  • dtype (optional): This is the data type of the output array.
  • out (optional): This is the alternate array where the result is placed.

Return value

The numpy.cumprod() function returns an output array that holds the result.

Code example

import numpy as np
# Creating an array
x = np.array([1, 2, 3])
# Invoking the numpy.cumprod() function
myarray = np.cumprod(x, axis=0)
print(x)
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array x using the array() method.
  • Line 7: We invoke the np.cumprod() function on the array. The result is assigned to the variable myarray.
  • Line 9: We print the input array x.
  • Line 10: We print the variable myarray.

Free Resources