I would like to shift a column in a Pandas DataFrame
, but I haven't been able to find a method to do it from the documentation without rewriting the whole DF. Does anyone know how to do it?
DataFrame:
## 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 272
##5 nan 291
You need to use df.shift here
df.shift(i) shifts the entire dataframe by i units down.
So for i = 1
Input:
Output:
So run this script to get the expected output
If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:
Lets define the dataframe from your example by
Then you could manipulate the index of the second column by
and finally re-combine the single columns
Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.
Edit: Generally shifting is possible by
df[2].shift(1)
as already posted however would that cut-off the carryover.I suppose imports
First append new row with
NaN, NaN,...
at the end of DataFrame (df
).It will create new DF df2. Maybe there is more elegant way but this works.
Now you can shift it:
Trying to answer a personal problem and similar to yours I found on Pandas Doc what I think would answer this question:
Hope to help future questions in this matter.