Is there a method in numpy to multiply each element in an array?
I want to multiply all the elements in a numpy array. If there is an array of type [1,2,3,4,5]
I want to get the value 1*2*3*4*5
.
I tried this by creating my own method, but the size of the array is very large, it takes a very long time to calculate, because I am using numpy, it would be helpful if numpy supports this operation.
I tried to figure out how to do this, but I failed. Is there a way that accomplishes this operation? If there is, is there a way to get the values by ranks in the matrix?
source to share
I believe what you need is numpy.prod.
From the documentation :
<strong> Examples
By default, we calculate the product of all elements:
>>> np.prod([1.,2.]) 2.0
Even if the input array is two-dimensional:
>>> np.prod([[1.,2.],[3.,4.]]) 24.0
But we can also specify the axis along which to multiply:
>>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.])
So, for your case, you need:
>>> np.prod([1,2,3,4,5])
120
source to share
You can use something like this:
import numpy as np
my_array = np.array([1,2,3,4,5])
result = np.prod(my_array)
#Prints 1*2*3*4*5
print(result)
Here is the numpy.prod documentation
Below is an excerpt from the above link:
By default, we calculate the product of all elements:
>>> np.prod([1.,2.]) 2.0
Even if the input array is two-dimensional:
>>> np.prod([[1.,2.],[3.,4.]]) 24.0
But we can also specify the axis along which to multiply:
>>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.])
source to share