NumPy Products

M.Ramya

 How to Find the Product of Array Elements in NumPy

When working with arrays in NumPy, you often need to compute the product of the elements. NumPy provides simple functions to accomplish this.

 Basic Product of Array Elements
To calculate the product of all elements in an array, use the np.prod() function.




Program:

import numpy as np
arr = np.array([1, 2, 3, 4])
result = np.prod(arr)
print(result)

Output:

24

(Because 1 × 2 × 3 × 4 = 24)


Program:

import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])
result = np.prod([arr1, arr2])
print(result)

Output:

40320

(This is the product of all elements: 1 × 2 × 3 × 4 × 5 × 6 × 7 × 8 = 40320)

 Product Along an Axis

If you want to compute the product along a specific axis, you can specify the axis parameter in the np.prod() function.

Program:

Product along the first axis (axis=1):

import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])
result = np.prod([arr1, arr2], axis=1)
print(result)

Output:

[24 1680]

(First array product: 1 × 2 × 3 × 4 = 24,
Second array product: 5 × 6 × 7 × 8 = 1680)

Cumulative Product

Cumulative product refers to the sequential product of elements up to each index, and it can be calculated using np.cumprod().

Program:

Cumulative product of an array:

import numpy as np
arr = np.array([5, 6, 7, 8])
result = np.cumprod(arr)
print(result)

Output:

[5 30 210 1680]
(5, 5×6=30, 5×6×7=210, 5×6×7×8=1680)
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send