How to add a dataframe column based on two consecutive rows in another column
Question:
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?
Answers:
You can do
df["B"] = df['A'] + df['A'].shift(1, fill_value= 0.)
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?
You can do
df["B"] = df['A'] + df['A'].shift(1, fill_value= 0.)