numpy.prod() method in Python
In this article, we will learn about numpy.prod() method in Python.
Introduction:- numpy.prod() returns the product of an array with certain parameters defined.
Syntax:- numpy.prod(a, axis=None, dtype=None, out=None, keepdims=<bool_value>)
1. a= array_like –input array
2. axis= None,int or tuple of ints –it species the axis .
None – calculates the product of all elements in the array.
int – if negative, it calculates from last to the first axis.
a tuple of ints – the product of all the axes defined in tuples.
3. dtype= dtype (optional) — the type of the returned array with an accumulator in which multiplication is done. The default data type of a is used except a has less precision int dtype over the default platform type.
4. out= ndarray, optional — separate output array to store results. Above all, it can cast the results in other dtype.
5. keepdims= bool, optional — If keepdims is set to true, the axes are left in result with dimension size one, and the result will broadcast correctly against the input array. If it is set to default, the keepdims will not pass through prod method of sub-classes of ndarray but if set to the non-default value it will pass.
Examples of numpy.prod() method in Python
- To begin with, let’s print the product of the 1d array:-
import numpy as np a = [4,5] b = np.prod(a) #product of a print(b)
As a result, the following output is obtained: –
C:\Users\KIRA\Desktop>py 1d.py 20
- Likewise, print the product of a 2d array:-
import numpy as np a = [[4,5],[2,3]] b = np.prod(a) # product of 2d matrix print(b)
C:\Users\KIRA\Desktop>py 2d.py 120
- Similarly, print the product of 2d array with axis 1 which is similar to a matrix multiplication of 2 arrays:-
import numpy as np a = [[4,5],[2,3]] b = np.prod(a,axis=1) # axis changes the multiplication to matrix multiplication print(b)
C:\Users\KIRA\Desktop>py axis.py [20 6]
- In addition, print the data type of the resultant array:-
import numpy as np a = np.array([10,20,30],dtype= np.int32) # keeping int32 as data type b = np.prod(a) print(b.dtype)
C:\Users\KIRA\Desktop>py dtype.py int32
The Numpy module has many other functions for programming too.