Peter Smit Peter Smit - 2 months ago 8
Python Question

How can I get the product of all elements in a one dimensional numpy array

I have a one dimensional NumPy array:

a = numpy.array([2,3,3])


I would like to have the product of all elements, 18 in this case.

The only way I could find to do this would be:

b = reduce(lambda x,y: x*y, a)


Which looks pretty, but is not very fast (I need to do this a lot).

Is there a numpy method that does this? If not, what is the most efficient way of doing this? My real world arrays have 39 float elements.

Answer

In NumPy you can try:

numpy.prod(a)

For a larger array numpy.arange(1,40) / 10.:

array([ 0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ,  1.1,
        1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9,  2. ,  2.1,  2.2,
        2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9,  3. ,  3.1,  3.2,  3.3,
        3.4,  3.5,  3.6,  3.7,  3.8,  3.9])

your reduce(lambda x,y: x*y, a) needs 24.2µs,

numpy.prod(a) needs 3.9µs.

EDIT: a.prod() needs 2.67µs. Thanks to J.F. Sebastian!