Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading