Home > Software engineering >  How to add a dataframe column based on two consecutive rows in another column
How to add a dataframe column based on two consecutive rows in another column

Time:01-25

I have column (A) in this pandas dataframe

A B
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?

CodePudding user response:

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)

res

CodePudding user response:

You can do

df["B"] = df['A']   df['A'].shift(1, fill_value= 0.)
  • Related