AppDividend
Latest Code Tutorials

np.product: How to Find Product of Array in Python

To find a product of array in Python, use the numpy prod() method. It returns the product of an array provided by a given axis.

np.product

The np.prod() is a numpy mathematical library method that returns the product of the array of elements over a given axis. By default, the axis is set to None, thereby calculating the product of all the elements in the given array. The prod() function takes up to seven arguments in which some can be optional.

Syntax

numpy.prod(arr1, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Parameters

arr1: It is a parameter to be interpreted as array_like, acting as the input data.

axis:  [Optional parameter] It can be int, a tuple of ints, or None. This parameter specifies the axes along which the product is to be performed. For the negative axis, the product is calculated from the last to the first axThe the product is performed on all the specified for a tuple of ints.

dtype: [Optional parameter] It specifies the type of the returned array. It also sets the accumulator in which the elements of the input array arr1 are to be multiplied. Unless arr1 has an integer dtype of less precision than the default platform integer, the dtype of arr1 is used by default. If arr1 is signed, then dtype is platform integer or an unsigned integer of the same precision if arr1 is unsigned.

out: (ndarray) [Optional parameter]: It specifies an alternate output array in which the resulting product is to be placed. This must have the same shape as the expected output.

keepdims: (bool) [Optional parameter] If set to true, the reduced axes are left as dimensions with size one in the result. It is done to make the resulting broadcast properly against the array taken as input.

initial: (scalar) [Optional parameter]: It is the starting value for the product.

where: (array_like of bool) [Optional parameter]: These are the elements to be included in the product.

Return Value

The product of an array of elements over a given axis. Returns array reference to out if specified.

 

Numpy prod

Note:

  1. If the input array is blank, then this method returns the neutral element: 1

Consider the following examples.

The following code demonstrates the use of the prod() method.

import numpy as np

arr1 = [5, 6]
arr2 = np.prod(arr1)
print(arr2)

Output

30

The following example demonstrates the case where a 2D array is used.

import numpy as np

arr1 = [[4,5],[1,3]]
arr2 = np.prod(arr1)
print(arr2)

Output

60

Passing an empty array

If we pass an empty array to prod() function, it will return 1 as an output. The following code demonstrates the case where an empty array is passed as an input array.

import numpy as np

arr1 = []
arr2 = np.prod(arr1)
print(arr2)

Output

1.0

If we pass the empty array then, the output of the empty array product is 1.

Assigning dtype = unsigned integer

The following code example demonstrates the case where dtype is unsigned integer, and so output type is taken as an unsigned platform integer.

import numpy as np

arr1 = [5, 22, 13]
arr2 = np.prod(arr1, dtype=np.uint8)
print(arr2.dtype == np.uint8)


arr1 = np.array([5, 22, 13], dtype=np.uint8)
print(np.prod(arr1).dtype == np.uint)
print(np.prod(arr1).dtype == np.uint8)

Output

True
True
False

The following code demonstrates the use of the where parameter to specify which elements to include in the product.

import numpy as np

arr1 = [10, 2, np.nan]
arr2 = np.prod(arr1, where=[True, True, False])
print(arr2)

Output

20.0

Passing an initial parameter

The following example demonstrates the use of the initial parameter to start the product with a value other than 1.

import numpy as np

arr1 = [1, 3, 4]
arr2 = np.prod(arr1, initial=100)
print(arr2)

Output

1200

The following code demonstrates the application of this method in a simple programming context.

In a factory, some workers are paid wages depending on the number of days they work in a month. There are various departments in the factory. As the manager, calculate the total wage that has to be paid for the workers in a month after looking at data in the format [[number of workers, daily wage, number of days], …] for the n departments of the factory.

See the following code.

import numpy as np

n = int(input("Number of departments: "))
alldata = []

for i in range(3*n):
    alldata.append(int(input()))

deptwisedata = np.reshape(alldata, (n, 3))
print(deptwisedata, "\n")

dept_total = np.prod(deptwisedata, axis=1)
print("Department total: ", dept_total, "\n")

grandtotal = sum(dept_total)
print("Grand total: ", grandtotal, "\n")

Output

Test Case 1:
->python3 example8.py
Number of departments: 2
5
4
6
6
1
2
[[5 4 6]
 [6 1 2]] 

Department total:  [120  12] 

Grand total:  132 

Test Case 2:
Number of departments: 3
6
1
10
5
2
6
6
1
10
[[ 6  1 10]
 [ 5  2  6]
 [ 6  1 10]] 

Department total:  [60 60 60] 

Grand total:  180

Conclusion

Numpy prod() returns the product of array elements over the given axis. The prod() function takes seven parameters at max and returns the product of array elements.

That’s it for the np.prod() function tutorial.

See also

Numpy divide()

Numpy square()

Numpy log

Numpy log2

Numpy log10

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.