Creating a new column that shows percent change based on values of another column

This is my dataframe:

df = pd.DataFrame({'a': [10, 20, 50]})

And this is the output that I want:

    a      b      
0  10    100
1  20    20  
2  50    10

I have an initial value which is 1000. Then I want to create column b. The first row of b is 10 percent of 1000 which is 100. The second row is 20 percent of 100 that we got previously. And the last row is 50 percent of 20.

I have tried this code but it doesn’t work:

df = df.reset_index(drop=True)
df.loc[0, 'b'] = 1000 * (df.a.iloc[0] / 100)
df['b'] = (df.a / 100) * df.b.shift(1)

>Solution :

Are you looking for cumprod?

(df['a'] / 100).cumprod() * 1000

0    100.0
1     20.0
2     10.0
Name: a, dtype: float64

Explanation: First divide by 100 since we’re dealing with percentages. Then find cumulative product of the series. Finally multiply by 1000 which is your starting value.


df['b'] = (df['a'] / 100).cumprod() * 1000
df
    a      b
0  10  100.0
1  20   20.0
2  50   10.0

Leave a Reply