0

This is my DataFrame:

col1 col2

A   5
B   3
C   8
D   2
E   9
F   9
G   4
H   9
I   3
J   5
K   7
L   3
M   7

I want to shift column col2 by 5 units forward. Expected output:

col1 col2
A   na
B   na
C   na
D   na
E   na
F   5
G   3
H   8
I   2
J   9
K   9
L   4
M   9
na  3
na  5
na  7
na  3
na  7

I know about the existence of the shift method, but it shifts the whole DataFrame

Igor K.
  • 813
  • 6
  • 17

2 Answers2

2

Do,

df['col2'] = df['col2'].shift(5)

You will get the following output

   col1  col2
0     A   NaN
1     B   NaN
2     C   NaN
3     D   NaN
4     E   NaN
5     F   5.0
6     G   3.0
7     H   8.0
8     I   2.0
9     J   9.0
10    K   9.0
11    L   4.0
12    M   9.0

But from the updated Q, I can see that the col1 should be extended as well. So do this instead,

df['col2'].index = df['col2'].index + 5
pd.concat([df['col1'], df['col2']], axis=1)

   col1  col2
0     A   NaN
1     B   NaN
2     C   NaN
3     D   NaN
4     E   NaN
5     F   5.0
6     G   3.0
7     H   8.0
8     I   2.0
9     J   9.0
10    K   9.0
11    L   4.0
12    M   9.0
13  NaN   3.0
14  NaN   5.0
15  NaN   7.0
16  NaN   3.0
17  NaN   7.0
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

Then:

df['col2'] = df['col2'].shift(5)
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74