How to add a dataframe column based on two consecutive rows in another column


I have column (A) in this pandas dataframe

1 1
1 2
2 3
5 7

Column (B) is created using the following formula:

col B (2)= col A(1)+ col A(2)

How do I create column (B) from column A?

Asked By: Marim medhat



Use shift() to get the rows one row down and add it back to column a.

df['b'] = df['a'] + df['a'].shift(fill_value=0)


Answered By: cottontail

You can do

df["B"] = df['A'] + df['A'].shift(1, fill_value= 0.)
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.