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

十年热恋 提交于 2019-12-01 21:59:21

问题


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?


回答1:


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



回答2:


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 documentation of numpy.prod
Below is a excerpt from the link above:

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.])


来源:https://stackoverflow.com/questions/44212854/is-there-a-method-in-numpy-to-multiply-every-element-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!