ufunc Products
NumPy's product ufuncs, such as prod and cumprod, allow efficient computation of products across arrays or along specific axes.
Key Topics
Total Product
The prod function computes the product of all elements in an array or along a specified axis.
Example
# Total product
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
total_product = np.prod(arr)
product_rows = np.prod(arr, axis=1)
product_columns = np.prod(arr, axis=0)
print("Total product:", total_product)
print("Row-wise product:", product_rows)
print("Column-wise product:", product_columns)
Output
Total product: 720
Row-wise product: [6 120]
Column-wise product: [4 10 18]
Row-wise product: [6 120]
Column-wise product: [4 10 18]
Explanation: The prod ufunc multiplies array elements, either across the entire array or along specified axes.
Cumulative Product
The cumprod function computes the cumulative product of array elements, producing an array where each element is the product of all previous elements.
Example
# Cumulative product
cumulative_product = np.cumprod(arr)
print("Cumulative product:", cumulative_product)
Output
Cumulative product: [1 2 6 24 120 720]
Explanation: The cumprod ufunc calculates cumulative products, which are useful in tracking progressive multiplicative totals.
Key Takeaways
- Total Product: Use
prodto compute products across arrays or axes. - Cumulative Product: Use
cumprodfor progressive multiplication of array elements. - Applications: Useful in factorial computations, growth analysis, and probabilistic models.