Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial sums and products in numpy

Tags:

python

numpy

I'm trying to build an array of partial products of the entries of another array in numpy. So far I have:

from numpy.random import dirichlet
from numpy import ones, prod

alpha = ones(100)
p = dirichlet(alpha)

I know I can whatever partial product by slicing my array. For example:

q = prod(p[0:10])

returns the product of the first 10 entries of p.

How could I build the array q so that entry i is the product of the i-1 previous values of p?

I've tried:

for i in p:
    q[i+1] = prod(p[0:i-1])

however, this throws a numpy.float64 doesn't support item assignment error.

How would I go about building this array? For sums, could I just replace prod with sum?

like image 941
Tom Kealy Avatar asked Oct 29 '25 16:10

Tom Kealy


1 Answers

You want the NumPy functions cumprod and cumsum

from numpy import cumprod, cumsum
# your code here
q = cumprod(p)
r = cumsum(p)

Documentation

  • http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumprod.html
  • http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html
like image 98
YXD Avatar answered Oct 31 '25 05:10

YXD