Skip to content
Advertisement

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement