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?
You want the NumPy functions cumprod and cumsum
from numpy import cumprod, cumsum
# your code here
q = cumprod(p)
r = cumsum(p)
Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With