Track compounded values
Compute running totals of multiplicative quantities such as growth factors or conversion rates.
NumPy · Function
Returns running products of array elements along a selected axis. Without axis, it flattens the input; dtype controls multiplication and output types, and out can reuse an existing array.
np.cumprod returns running products along a chosen axis. With no axis, it flattens the input first; dtype controls the accumulator and result type, while out can receive the result in a supplied array.
numpy.cumprod(a, axis=None, dtype=None, out=None)| Name | Type | Description |
|---|---|---|
a | array_like | Input array. |
axis | int, optional | Axis along which the cumulative product is computed. If omitted, the input is flattened. |
dtype | dtype, optional | Type of the returned array and the accumulator used for multiplication. |
out | ndarray, optional | Existing output array for the result; its shape and buffer length must match the expected output. |
An ndarray containing the cumulative products, with the shape determined by the input and axis; if out is supplied, the result is written there.
import numpy as np
values = np.array([[1, 2, 3], [4, 5, 6]])
print(np.cumprod(values, axis=1))
# [[ 1 2 6]
# [ 4 20 120]]Computes running products independently across each row.
Compute running totals of multiplicative quantities such as growth factors or conversion rates.
Generate prefix products independently across rows or columns of a matrix.
Control numeric representation or write into preallocated storage.
It computes each prefix product along the selected axis: every output element multiplies the corresponding input element by the preceding cumulative result. If axis is omitted, the input is flattened first.
Follow-up: How would you compute row-wise products for a 2-D array? Pass axis=1; axis=0 instead produces cumulative products down columns.
dtype determines both the result array type and the accumulator type used during multiplication. If omitted, NumPy generally follows the input dtype, with a platform-integer rule for narrower integer inputs.
Follow-up: Why might dtype=np.float64 be useful? It can provide a wider numeric range and floating-point output, though floating-point overflow remains possible.
out is an optional ndarray that receives the computed result instead of requiring a newly allocated destination. It must have the expected shape and buffer length, and values may be cast to its type.
Follow-up: What should be checked before supplying out? Confirm its dimensions and capacity, and ensure its dtype can represent the intended result adequately.
numpy.ndarray.cumprodnumpy.prodnumpy.cumsum