Pandas: multiply starting value for one column through each value in another within group

Viewed 103

I have a starting value and some future expected growth rates for a number of customers.

Here is a simple sample dataframe:

df = pd.DataFrame([['A',1,10,np.nan],['A',2,10,1.2],['A',3,10,1.15],
                  ['B',1,20,np.nan],['B',2,20,1.05],['B',3,20,1.2]],columns = ['Cust','Period','startingValue','Growth'])
print df 

  Cust  Period  startingValue  Growth
0    A       1             10     NaN
1    A       2             10    1.20
2    A       3             10    1.15
3    B       1             20     NaN
4    B       2             20    1.05
5    B       3             20    1.20

For each Cust, I want to multiply the starting value by the growth rate, then carry that value forward to the next period. I could do this with groupby-apply or an ugly for loop, but I'm hoping there's some faster vectorized method for doing this. I had hoped there would be some .fill() magic, where you could multiply by another column as it fills downwards. Here's what the output should look like:

 Cust  Period  startingValue  Growth  Pred_val
0    A       1             10     NaN      10.0
1    A       2             10    1.20      12.0
2    A       3             10    1.15      13.8
3    B       1             20     NaN      20.0
4    B       2             20    1.05      21.0
5    B       3             20    1.20      25.2

Thoughts?

1 Answers
Related