简体   繁体   中英

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!

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM