Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add two Values from the same columns?

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

….

# column1   colum2
     1         3
     2         4
     2         6
     4

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading