3

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] 

1 Answer 1

4

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])
Sign up to request clarification or add additional context in comments.

2 Comments

You did solve my particular problem, but what about a general case where you can't ignore the value of a?
@enedene: You could do b[0] *= a[0] before calling cumprod if you could modify b, or multiply the whole result by a[0] (i.e. cumprod(...) * a[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.