简体   繁体   中英

Numpy array - change the next element based on a change on previous

Let's say I have two numpy arrays:

import numpy as np
a = np.ones(5)
b = np.array([1.0, 1.1, 1.05, 1.2, 1.25])

I'd like that element a[1]=a[0]*b[1] , lets call this a[1] a new_a , then a[2]=new_a*b[2] . Can this be done without using a loop in numpy? With a loop code looks like this:

for i in range(len(a)-1):
    a[i+1] = a[i]*b[i+1]
print (a)

prints:

[ 1.      1.1     1.155   1.386   1.7325] 

This is called "cumulative product". There is already a built-in function cumprod for this.

>>> numpy.cumprod([1.0, 1.1, 1.05, 1.2, 1.25])
array([ 1.    ,  1.1   ,  1.155 ,  1.386 ,  1.7325])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM