Add previous row value to current row and so on Python

Viewed 549

Hi the following is my DataSet

           MD  Incl.    Azi.
0        0.00   0.00  350.00
1      161.00   0.00  350.00
2      261.00   0.00  350.00
3      361.00   0.00  350.00
4      461.00   0.00  350.00

I would like to perform a calculation, create a new column and in this column add the row value to the previous row value in the column and so on.

import pandas as pd
import math
import numpy as np

#open excel file
df = pd.read_excel
print(df)

for i in range (1, len(df)):
    incl = np.deg2rad(df['Incl.'])
    df['TVD_diff'] = (((df['MD'] - df['MD'].shift())/2)*(np.cos(incl).shift() + np.cos(incl)))

print(df)

           MD  Incl.    Azi.         TVD
0        0.00   0.00  350.00         NaN
1      161.00   0.00  350.00  161.000000
2      261.00   0.00  350.00  100.000000
3      361.00   0.00  350.00  100.000000
4      461.00   0.00  350.00  100.000000

I would like the TVD column to be

TVD
NaN
161
261
361
461

and so on by adding its current value to the value before

1 Answers

Use cumsum

df['tvd'] = df['tvd'].cumsum()

Example:

import pandas as pd
import numpy as np
from io import StringIO

txt = """           MD  Incl.    Azi.
0        0.00   0.00  350.00
1      161.00   0.00  350.00
2      261.00   0.00  350.00
3      361.00   0.00  350.00
4      461.00   0.00  350.00"""

df = pd.read_csv(StringIO(txt), sep='\s\s+')

for i in range (1, len(df)):
    incl = np.deg2rad(df['Incl.'])
    df['TVD_diff'] = (((df['MD'] - df['MD'].shift())/2)*(np.cos(incl).shift() + np.cos(incl)))

df['TVD_diff'] = df['TVD_diff'].cumsum()

print(df)

Output:

      MD  Incl.   Azi.  TVD_diff
0    0.0    0.0  350.0       NaN
1  161.0    0.0  350.0     161.0
2  261.0    0.0  350.0     261.0
3  361.0    0.0  350.0     361.0
4  461.0    0.0  350.0     461.0
Related