Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe - Shifting rows down and maintaining data

My original Dataframe (df):

    column1  column2
0   1        a
1   2        b
2   3        c
3   4        d
4   5        e
5   6        f

I want to shift the values down by 6 like so:

    column1 column2
0       
1       
2       
3       
4       
5       
6   1        a
7   2        b
8   3        c
9   4        d
10  5        e
11  6        f

When I use df = df.shift(6), I end up loosing data.

I found this post (How to shift a column in Pandas DataFrame without losing value) but it only seems to work if the values are shifted down by 1.

How can I shift multiple spots down while retaining the data?

like image 671
andyb88 Avatar asked Oct 18 '25 03:10

andyb88


1 Answers

You can try

df.index = df.index+6
df = df.reindex(np.arange(12))

    column1 column2
0   NaN     NaN
1   NaN     NaN
2   NaN     NaN
3   NaN     NaN
4   NaN     NaN
5   NaN     NaN
6   1.0     a
7   2.0     b
8   3.0     c
9   4.0     d
10  5.0     e
11  6.0     f
like image 84
Vaishali Avatar answered Oct 20 '25 18:10

Vaishali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!