Open In App

Numpy.prod() in Python

Improve
Improve
Like Article
Like
Save
Share
Report

numpy.prod() returns the product of array elements over a given axis. 
Syntax: 
 

numpy.prod(a, axis=None, dtype=None, out=None, keepdims=)

Parameters 
a : array_like 
Its the input data. 
axis : None or int or tuple of ints, its optional 
It is theAxis or axes along which a product is performed. The default axis is None, it will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis. 
If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. 
dtype : dtype, its optional 
It is the type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. 
out : ndarray, its optional 
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. 
keepdims : bool, optional 
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
Example 1 
 

Python




# Python Program illustrating
# working of prod()
 
import numpy as np
array1 = [1, 2]
 
# applying function
array2 = np.prod(array1)
 
print("product", array2)


Output: 
 

2.0

Example 2 
A 2d array 
 

Python




import numpy as np
array1 = [[1., 2.], [3., 4.]]
 
# applying function
array2 = np.prod(array1)
 
print("product", array2)


Output: 
 

24.0

Example 3 
The product of an empty array will be neutral element 1: 
 

Python




import numpy as np
array1 = []
 
# applying function
array2 = np.prod(array1)
 
print("product", array2)


Output: 
 

1

Example 4 
By specifying the axis over which we are multiplying 
 

Python




import numpy as np
array1 =[[1, 2], [3, 4]]
 
# applying function
array2 = np.prod(array1, axis = 1)
 
print("product", array2)


Output: 
 

[2, 12]

Example 5 
If the type of x is unsigned, then the output type will the unsigned platform integer 
 

Python




import numpy as np
x = np.array([1, 2, 3], dtype = np.uint8)
 
# applying function
 np.prod(x).dtype == np.uint


Output: 
 

True

 



Last Updated : 12 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads