4

I would like to shift a column in a Pandas DataFrame, but I haven't been able to find a method to do it without losing values. (This post is quite similar to How to shift a column in Pandas DataFrame but the validated answer doesn't give the desired output and I can't comment it). Does anyone know how to do it?

##    x1   x2
##0  206  214
##1  226  234
##2  245  253
##3  265  272
##4  283  291

Desired output:

##    x1   x2
##0  206  nan
##1  226  214
##2  245  234
##3  265  253
##4  283  271
##5  nan  291
Community
  • 1
  • 1
Vixare
  • 73
  • 1
  • 5
  • 1
    Possible duplicate of [How to shift a column in Pandas DataFrame](https://stackoverflow.com/questions/10982089/how-to-shift-a-column-in-pandas-dataframe) – Kay Wittig Jul 09 '18 at 18:24

1 Answers1

11

Use loc to add a new blank row to the DataFrame, then perform the shift.

df.loc[max(df.index)+1, :] = None
df.x2 = df.x2.shift(1)

The code above assumes that your index is integer based, which is the pandas default. If you're using a non-integer based index, replace max(df.index)+1 with whatever you want the new last index to be.

root
  • 32,715
  • 6
  • 74
  • 87