Create a column where the values are caculated on previously caculated values

Question:

I am wondering if there’s a way to do multiplication with a previously derived value in the newly created column.

import pandas as pd
df = {1: {0: 100.0, 1: 0.96, 2: 0.93, 3: 0.88, 4: 0.85, 5: 0.8}}

        1
0  100.00
1    0.96
2    0.93
3    0.88
4    0.85
5    0.80

Logic:
1) 1 = 1
2) 0.96 * 1 (previously derived value) = 0.96
3) 0.93 * (0.96) (previously derived value) = 0.8928
4) 0.88 * (0.8928) (previously derived value) = 0.785664

Expected output:

        1           2
0     1.0         1.0
1    0.96        0.96
2    0.93      0.8928
3    0.88    0.785664
4    0.85   0.6678144
5    0.80  0.53425152
Asked By: codedancer

||

Answers:

You want a cumprod, divided by the first value:

df[2] = df[1].cumprod().div(df[1].iloc[0])

Output:


        1         2
0  100.00  1.000000
1    0.96  0.960000
2    0.93  0.892800
3    0.88  0.785664
4    0.85  0.667814
5    0.80  0.534252
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.