Johan Jomy
Johan Jomy

Reputation: 691

Shift a Column by one column from a row with pandas

I want to shift the column1 form index 2 1 step down with pandas i want to make my data from _from to _to

_from =
   Column1  Column2  Column3
0     1     20.0       19
1     2     21.0       23
2     3     33.0       34
3     4     42.0       35

_to =

   Column1  Column2  Column3
0     1     20.0       19
1     2     21.0       23
2     Nan   33.0       34
3     3     42.0       35

I tried df.Column1 = df.Column1.shift(+1) but it shifts from the top like this:

   Column1  Column2  Column3
0     Nan     20.0       19
1     1       21.0       23
2     2       33.0       34
3     3       42.0       35

Thanks!

Upvotes: 3

Views: 424

Answers (2)

zoldxk
zoldxk

Reputation: 1

df.Column1[2:] = df.Column1[2:].shift(+1)

out:

  Column1  Column2  Column3
0      1.0     20.0       19
1      2.0     21.0       23
2      NaN     33.0       34
3      3.0     42.0       35

Upvotes: 1

Umar.H
Umar.H

Reputation: 23099

use .iloc and assign your new column.

df.iloc[2:, 0] = df.iloc[2:, 0].shift(1)


   Column1  Column2  Column3
0      1.0     20.0       19
1      2.0     21.0       23
2      NaN     33.0       34
3      3.0     42.0       35

Upvotes: 4

Related Questions