NumPy ufunc Products
NumPy's prod and cumprod ufuncs multiply array elements together, either collapsing them into a single total or tracking the running product at every step along the way.
Multiplying Arrays with prod()
np.prod() is the multiplicative counterpart to np.sum(): instead of adding every element together, it multiplies them all. Like sum(), it accepts an axis parameter to reduce along rows or columns of a multi-dimensional array.
Example
import numpy as np
values = np.array([1, 2, 3, 4])
print(np.prod(values))
# 24
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.prod(matrix, axis=0)) # [ 4 10 18]
print(np.prod(matrix, axis=1)) # [ 6 120]Running Products with cumprod()
np.cumprod() mirrors cumsum(), but multiplies instead of adds. It returns an array the same length as the input, where each entry is the product of every element up to and including that position — perfect for compounding growth rates.
Example
import numpy as np
growth_factors = np.array([1.05, 1.02, 0.98, 1.10])
running_product = np.cumprod(growth_factors)
print(running_product)
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.cumprod(matrix, axis=1))
# [[ 1 2 6]
# [ 4 20 120]]Practical Uses: Factorials and Compound Growth
prod() is a natural way to compute a factorial, since n! is just the product of every integer from 1 to n. cumprod() is a natural way to track compound growth, such as an investment balance multiplied by a different yearly growth rate each year.
Example
import numpy as np
# 5! using prod of 1..5
n = 5
factorial_n = np.prod(np.arange(1, n + 1))
print(factorial_n)
# 120
# $1000 invested, growing by these yearly rates
principal = 1000
yearly_growth = np.array([1.07, 1.05, 1.09, 1.02])
balance_each_year = principal * np.cumprod(yearly_growth)
print(balance_each_year)- np.prod() is the multiplicative counterpart to np.sum(): both are reductions, but one adds and the other multiplies.
- An empty array passed to prod() returns 1.0, the multiplicative identity, just as an empty array passed to sum() returns 0.
- Integer products can overflow the default integer dtype surprisingly quickly; use dtype=np.int64 or floats for large products.
- cumprod() is to prod() what cumsum() is to sum(): it keeps every intermediate multiplication instead of only the final result.
Exercise: NumPy ufunc Products
What does np.prod([1, 2, 3, 4]) calculate?