Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method in numpy to multiply every element in an array?

I want to multiply all elements in a numpy array. If there's an array like [1, 2, 3, 4, 5], I want to get value of 1 * 2 * 3 * 4 * 5.

I tried this by making my own method, but size of array is very large, it takes very longs time to calculate because I'm using numpy it would be helpful if numpy supports this operation.

I tried to find out through numpy documents, but I failed. Is there a method which does this operation? If there is, is there a way to get values along a rank in an matrix?

like image 371
bj1123 Avatar asked May 27 '17 04:05

bj1123


People also ask

How do you multiply every element in a NumPy array?

You can use np. multiply to multiply two same-sized arrays together. This computes something called the Hadamard product. In the Hadamard product, the two inputs have the same shape, and the output contains the element-wise product of each of the input values.

How do you multiply all values in a NumPy array by scalar?

Method 1: Multiply NumPy array by a scalar using the * operator. The first method to multiply the NumPy array is the use of the ' * ' operator. It will directly multiply all the elements of the NumPy array whether it is a Single Dimensional or Multi-Dimensional array.

How do I multiply an element by NumPy element?

multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.


1 Answers

I believe what you need is, numpy.prod.

From the documentation:

Examples

By default, calculate the product of all elements:

>>> np.prod([1.,2.])
2.0

Even when the input array is two-dimensional:

>>> np.prod([[1.,2.],[3.,4.]])
24.0

But we can also specify the axis over 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
like image 145
Wasi Ahmad Avatar answered Oct 16 '22 07:10

Wasi Ahmad