Reputation: 941
I want to perform the following calculations with my df. I've done this in Excel but I'm not sure how to do this using Python. Here's the calculation
initial| recursion begins
Name | 1 | 2 | 3 | 4 ...
------------------------------------------------
A | A1 | A2 | A3 | A4 <--given
a | a1=0 | a2=c1*A2 | a3=c2*A3 | a4=c3*A4 <--calculation (1st cell always = 0)
c | c1=1 | c2=c1-a2 | c3=c2-a3 | c4=c3-a4 <--calculation (1st cell always 1)
Here's my example:
df
Name 1 2 3 4 5
----------------------------------
A 0 .125 .286 .25 .333
B 0 0 0 .5 -
the output would be:
Name 1 2 3 4 5
----------------------------------
A 0 .125 .286 .25 .333
Ax 0 .125 .25 .156 .156
Ay 1 .875 .625 .469 .313
B 0 .1 0 .25 -
Bx 0 .1 0 .225 -
By 1 .9 .9 .675 -
Thank you!
Upvotes: 1
Views: 92
Reputation: 323226
Let me explain a little bit .
a2=c1*A2;c2=c1-a2, then c2=c1-a2=c1-c1*A2=c1(1-A2)
,
c3 should be c3=c2(1-A3)=c1(1-A2)(1-A3)
, that is where(1-df).cumprod(1)
, come from
df=df.set_index('Name')
df1=(1-df).cumprod(1)
df2=df1.shift(1,axis=1).mul(df)
pd.concat([df,df1,df2],keys=['','x','y']).fillna({'1':0})
Out[769]:
1 2 3 4 5
Name
A 0.0 0.125 0.28600 0.250000 0.333000
B 0.0 0.000 0.00000 0.500000 NaN
x A 1.0 0.875 0.62475 0.468562 0.312531
B 1.0 1.000 1.00000 0.500000 NaN
y A 0.0 0.125 0.25025 0.156187 0.156031
B 0.0 0.000 0.00000 0.500000 NaN
Upvotes: 2