0

My dataframe currently looks like this:

     ts1   ts2
0     0     NaN
1     3     NaN
2     2     NaN
3     5     NaN

.... and so on to row 1000

I need to populate column ts2 with the below code from x=1 til x=1000. Can someone please show me how to simplify this maybe by using for loops?

df.at[0,'ts2']=0 #start ts2 row 0 at 0
x = 1
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
x = 2
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
x = 3
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
x = 4
df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
#.....
#x = 1000
#df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']
df

I have tried to replace all NaN with 0s and also use the following code but no luck:

for x in range(1,1000):
    df.at[x,'ts2']=df.at[x,'ts1'] + df.at[x-1,'ts2']

I would like the end result to look like this:

     ts1   ts2
0     0     0
1     3     3  #3+0
2     2     5  #2+3
3     5     10 #5+5
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51

1 Answers1

1
df = pd.DataFrame({"ts1":[0, 3, 2, 5]})
df['ts2'] = df.ts1.cumsum()
Tom Ron
  • 5,906
  • 3
  • 22
  • 38