Perform Calculation on Every Row, Except The First - Pandas

Viewed 29

I have three columns: year, return, growth_of_1k. What I'd like to so is calculate the growth of $1,000 using the return column, and save it to growth_of_1k.

To visualize, here's what my dataframe currently looks like:

year return growth_of_1k
2010 0.1 1000
2011 0.4 NaN
2012 0.3 NaN

What I'd like to do is take the previous year's growth_of_1k and multiply it by this year's return.

Right now I have this:

df['growth_of_1k'] = df['growth_of_1k'].shift(1) * (1 + df['return'])

However, the code above only updates the second row, and nothing else. Any idea on how I can accomplish this?

2 Answers

Let's try cumprod:

df['return'].where(np.arange(len(df))>0, 0).add(1).cumprod() * df.loc[0, 'growth_of_1k']

output:

0    1000.0
1    1400.0
2    1820.0
Name: return, dtype: float64

Here's one way to do it:

df.loc[df.index[1:], 'growth_of_1k'] = (df.loc[df.index[1:], 'return'] + 1).cumprod() * df.growth_of_1k.iat[0]

Output:

   year  return  growth_of_1k
0  2010     0.1        1000.0
1  2011     0.4        1400.0
2  2012     0.3        1820.0
Related