Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas DataFrame offset column

I have a DataFrame with thousands of lines and I need to offset all items in column A 1 row up to get values like in column B. I can loose item from row 0 and I'll fill down the last row with item from the row above. I just don't know how to cut and paste everything 1 up.

     A   B
0    0   0
1    0   1
2    1   1
3    1   1
4    1   1
5    1   2
6    2   2
7    2   2
8    2   3
9    3   3
10   3   4
11   4   4
12   4   4
13   4   4
like image 248
Bartek Nowakowski Avatar asked Oct 25 '25 12:10

Bartek Nowakowski


1 Answers

IIUC ffill and shift

df['A'] = df['A'].shift(-1).ffill()
print(df)
    A  B
0   0.0  0
1   1.0  1
2   1.0  1
3   1.0  1
4   1.0  1
5   2.0  2
6   2.0  2
7   2.0  2
8   3.0  3
9   3.0  3
10  4.0  4
11  4.0  4
12  4.0  4
13  4.0  4
like image 177
Umar.H Avatar answered Oct 27 '25 02:10

Umar.H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!