spitfiredd
spitfiredd

Reputation: 3135

Pandas Shift columns but add new rows where non-shifted columns are null

Say I have a dataframe:

  x y
0 1 5
1 2 4
2 3 3
3 4 2
4 5 1

I want to run something like df.y.shift(3) and it will not only shift y down 3 rows but also create three new rows for x that are null so that the dataframe becomes

  x y
0 1 N
1 2 N
2 3 N
3 4 5
4 5 4
5 N 3
6 N 2
7 N 1

Where N=NaN

The shift operator only seems to shift a column down n rows but will also "knock" n items from your list. I want to keep those n item on my new dataframe.

Upvotes: 0

Views: 60

Answers (1)

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

You can reindex first, and then shift only one of the columns:

df = df.reindex(range(8))
df["y"] = df.y.shift(3)

     x    y
0  1.0  NaN
1  2.0  NaN
2  3.0  NaN
3  4.0  5.0
4  5.0  4.0
5  NaN  3.0
6  NaN  2.0
7  NaN  1.0

Upvotes: 1

Related Questions