0

I am trying to derive a calculated field using the value from columns of previous row which also a calculated field.

Input datafame:

         0         1          2    3    4    5
0  94000.0  9.970228 -21.062708  0.0  0.0  0.0
1      0.0  9.970228 -20.748142  0.0  0.0  0.0

Required output:

         0         1          2    3    4    5            d
0  94000.0  9.970228 -21.062708  0.0  0.0  0.0  9428.06934
1      0.0  9.970228 -20.748142  0.0  0.0  0.0  9407.00663

Code:

df= pd.DataFrame([(94000, 9.9702279, -21.0627081029071, 0, 0, 0), 
                (0, 10.1213880586432, -20.7481423282323, 0, 0, 0)])

df['d'] = (df[0]/df[1]).fillna(0) + ((df[0]/df[1]).shift(1) + d[2].shift(1)).fillna(0)  + 
           df[3].shift(1).fillna(0) +   df[4].shift(1) + df[5].shift(1)

Output which I am getting:

         0         1          2    3    4    5            d
0  94000.0  9.970228 -21.062708  0.0  0.0  0.0  9428.06934
1      0.0  9.970228 -20.748142  0.0  0.0  0.0  -20.748142

EDIT:

I refferd this Example example and now I am getting output as code:

df.loc[0, 'd'] = df.loc[0, 5]
for i in range(1, len(df)):
    df.loc[i, 'd'] = (df.loc[i, 0] / df.loc[i, 1]) + (df.loc[i-1, 0] / df.loc[i-1, 1]) +  df.loc[i-1, 2]

      0          1          2  3  4  5            d
0  94000   9.970228 -21.062708  0  0  0     0.000000
1      0  10.121388 -20.748142  0  0  0  9407.006634
Abhis
  • 585
  • 9
  • 25
  • Your first row `d` would be 0 because you're starting at 1, and the first row's index is 0. What would you want to do when the row above doesn't exist? – RCA Apr 06 '18 at 14:55

1 Answers1

0

Code:

import  pandas as pd
df = pd.DataFrame([(94000, 9.9702279, -21.0627081029071, 0, 0, 0),
                (0, 10.1213880586432, -20.7481423282323, 0, 0, 0),
                   (0, 9.6525370469631300, -21.7559382552248, 0, 0, 0)])

df.loc[0, 'd'] = df.loc[0, 5]
for i in range(0, len(df)):
    if i ==0:
        df.loc[i, 'd'] = (df.loc[i, 0] / df.loc[i, 1])

    else:
        df.loc[i, 'd'] =  (df.loc[i - 1, 'd']) + df.loc[i - 1, 2]

print(df)

Output:

       0          1          2  3  4  5            d
0  94000   9.970228 -21.062708  0  0  0  9428.069342
1      0  10.121388 -20.748142  0  0  0  9407.006634
2      0   9.652537 -21.755938  0  0  0  9386.258492
Abhis
  • 585
  • 9
  • 25