numpy中有没有一种方法可以将数组中的每个元素相乘? [英] Is there a method in numpy to multiply every element in an array?

查看:2333
本文介绍了numpy中有没有一种方法可以将数组中的每个元素相乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个numpy数组中的所有元素相乘.如果有类似[1,2,3,4,5]的数组,我想获取1*2*3*4*5的值.

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.

我通过制作自己的方法进行了尝试,但是数组的大小很大,因为我使用的是numpy,所以计算时间很长,如果numpy支持此操作会很有帮助.

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.

我试图通过numpy文档找出来,但是失败了.有没有执行此操作的方法?如果存在,是否有一种方法可以沿矩阵的等级获取值?

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?

推荐答案

我相信您需要的是numpy.prod.

I believe what you need is, numpy.prod.

文档:

示例

默认情况下,计算所有元素的乘积:

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

这篇关于numpy中有没有一种方法可以将数组中的每个元素相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆