Home > database >  Calculation of multiplicative percentages
Calculation of multiplicative percentages

Time:03-24

I am trying to calculate percent of percent. per, per1, and per1-per are in percentages

date      per    per1   per1-per
1/1/2021   0      0        0
2/1/2021   0      0        0
3/1/2021   2      3        1
4/1/2021   0      2        2
5/1/2021   5      1       -4
6/1/2021   0      0        0

my desired output would be

date      per    per1   per1-per  per_of_per
1/1/2021   0      0        0          0
2/1/2021   0      0        0          0
3/1/2021   2      3        1          1 
4/1/2021   0      2        2          3.02
5/1/2021   5      1       -4         -1.10
6/1/2021   0      0        0         -1.10

How per_of_per is calculated is:

  • for first time, per_of_per[0] = (1 per1-per[0])-1
  • for second time, per_of_per[1] = (1 per1-per[0])*(1 per1-per[1])-1
  • for third time, per_of_per[2] = (1 per1-per[0])*(1 per1-per[1])*(1 per1-per[2])-1 and so on..

CodePudding user response:

Use cumprod after converting percent to int, adding 1, then perform the reverse process to give back percent:

df['pre_per'] = df['per1-per'].div(100).add(1).cumprod().sub(1).mul(100)

output:

       date  per  per1  per1-per  pre_per
0  1/1/2021    0     0         0   0.0000
1  2/1/2021    0     0         0   0.0000
2  3/1/2021    2     3         1   1.0000
3  4/1/2021    0     2         2   3.0200
4  5/1/2021    5     1        -4  -1.1008
5  6/1/2021    0     0         0  -1.1008
  • Related