numpy 中是否有一种方法可以将数组中的每个元素相乘?
Is there a method in numpy to multiply every element in an array?
我想乘以 numpy 数组中的所有元素。如果有像 [1, 2, 3, 4, 5]
这样的数组,我想获取 1 * 2 * 3 * 4 * 5
.
的值
我通过自己的方法尝试了这个,但是数组的大小非常大,计算需要很长时间,因为我使用的是 numpy 如果 numpy 支持这个操作会很有帮助。
我试图通过numpy文档查找,但没有成功。是否有执行此操作的方法?如果有,有没有一种方法可以沿着矩阵中的等级获取值?
我相信你需要的是,numpy.prod。
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.])
所以对于你的情况,你需要:
>>> np.prod([1,2,3,4,5])
120
你可以这样使用:
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
以下是上面 link 的摘录:
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.])
除了其他答案之外,每个numpy.array
has got prod()
方法都可以使用。
示例如下:
>>> np.array([6, 2, 3]).prod()
36
我想乘以 numpy 数组中的所有元素。如果有像 [1, 2, 3, 4, 5]
这样的数组,我想获取 1 * 2 * 3 * 4 * 5
.
我通过自己的方法尝试了这个,但是数组的大小非常大,计算需要很长时间,因为我使用的是 numpy 如果 numpy 支持这个操作会很有帮助。
我试图通过numpy文档查找,但没有成功。是否有执行此操作的方法?如果有,有没有一种方法可以沿着矩阵中的等级获取值?
我相信你需要的是,numpy.prod。
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.])
所以对于你的情况,你需要:
>>> np.prod([1,2,3,4,5])
120
你可以这样使用:
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
以下是上面 link 的摘录:
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.])
除了其他答案之外,每个numpy.array
has got prod()
方法都可以使用。
示例如下:
>>> np.array([6, 2, 3]).prod()
36