NumPy Products

✖️ NumPy Products

NumPy provides functions to calculate the product of array elements, similar to summation but using multiplication. These operations are fast, vectorized, and can operate along specific axes in multi-dimensional arrays.


✅ 1. Product of All Elements (np.prod)

import numpy as np

arr = np.array([1, 2, 3, 4])
total_product = np.prod(arr)

print(total_product) # 24 (1*2*3*4)

  • Computes the product of all elements in the array


✅ 2. Product Along an Axis (2D Array)

arr2d = np.array([[1, 2, 3],
[4, 5, 6]])

# Product of each column (axis=0)
col_product = np.prod(arr2d, axis=0)
print("Column product:", col_product) # [4 10 18]

# Product of each row (axis=1)
row_product = np.prod(arr2d, axis=1)
print("Row product:", row_product) # [6 120]

  • axis=0 → multiply down the rows (column-wise)

  • axis=1 → multiply across columns (row-wise)


✅ 3. Cumulative Product (np.cumprod)

arr = np.array([1, 2, 3, 4])
cum_prod = np.cumprod(arr)

print(cum_prod) # [1 2 6 24]

  • Computes a running product of elements

arr2d = np.array([[1,2,3],[4,5,6]])
cum_prod_axis0 = np.cumprod(arr2d, axis=0)
cum_prod_axis1 = np.cumprod(arr2d, axis=1)

print("Cumulative product axis=0:\n", cum_prod_axis0)
# [[ 1 2 3]
# [ 4 10 18]]

print("Cumulative product axis=1:\n", cum_prod_axis1)
# [[ 1 2 6]
# [ 4 20 120]]


✅ 4. Product with Conditions

arr = np.array([1, 2, 3, 4, 5])
# Product of even numbers only
even_product = np.prod(arr[arr % 2 == 0])
print(even_product) # 8 (2*4)
  • Use Boolean indexing to multiply elements that satisfy a condition


✅ 5. Notes & Tips

  • np.prod works for 1D, 2D, or ND arrays

  • Axis parameter is useful for dimension-specific product

  • np.cumprod is handy for cumulative growth calculations (finance, probabilities)


🎯 Practice Exercises

  1. Compute the product of all elements in [1, 2, 3, 4, 5].

  2. Compute row-wise and column-wise products for [[2,3],[4,5]].

  3. Compute the cumulative product of [1, 2, 3, 4].

  4. Compute the product of all odd numbers in [1,2,3,4,5,6,7].

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *