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
While cumprod
is a good simple way of doing this, it would be good to understand why you got an error.
q = prod(p[0:10]) # q is now a float
for i in p:
q[i+1] = prod(p[0:i-1])
There are 2 problems with the iteration. i
is an item of p
, not an index. In fact it probably is a float. q[i+1]
does not work because q
is a float, not an array.
q=np.zeros(p.size+1)
for i in range(p.size):
q[i+1]=np.prod(p[:i])
This iteration works. Now q
is a large enough array, and i
is an integer, a valid index. Where it uses i
, i+1
or i-1
is something you can tweak.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.