Home > database >  How to add two Values from the same columns?
How to add two Values from the same columns?

Time:12-16

So i am looking to add 2 Values from a DataFrame Column and write the result in a second column.

column1 is given, column2 will be my result, what i want to do is:

column2[0] = column[0] column[1]

column2[1] = column[1] column[2]

....

# column1   colum2
     1         3
     2         4
     2         6
     4

CodePudding user response:

You can add the corresponding value in your 'column1' column, and it's previous value using shift(), and wrap the whole return in shift(-1) which will shift the values upward by 1 index position:

df['column2'] = (df.column1   df.column1.shift()).shift(-1)

print(df)

   column1  column2
0        1      3.0
1        2      4.0
2        2      6.0
3        4      NaN

If you don't use an outer shift(-1):

df['column3'] = df.column1   df.column1.shift()

print(df)

   column1  column2  column3
0        1      3.0      NaN
1        2      4.0      3.0
2        2      6.0      4.0
3        4      NaN      6.0
  • Related