Write a program in Python to shift a dataframe index by two periods in positive and negative direction


Assume, you have a dataframe and the shift index by two periods in positive and negative direction is,

shift the index by three periods in positive direction
                     Id Age
2020-01-01 00:00:00 NaN NaN
2020-01-01 12:00:00 NaN NaN
2020-01-02 00:00:00 1.0 10.0
2020-01-02 12:00:00 2.0 12.0
2020-01-03 00:00:00 3.0 14.0
shift the index by three periods in negative direction
                     Id Age
2020-01-01 00:00:00 3.0 14.0
2020-01-01 12:00:00 4.0 11.0
2020-01-02 00:00:00 5.0 13.0
2020-01-02 12:00:00 NaN NaN
2020-01-03 00:00:00 NaN NaN

Solution

To solve this, we will follow the steps given below −

  • Create pandas time series with start=’01-01-2020’, periods = 5, freq =’12H’

  • Define a dataframe

  • Apply, df.shift() to shift index by two periods in a positive direction as,

df.shift(2,axis=0)
  • Apply, df.shift() to shift index by two periods in a negative direction as,

df.shift(-2,axis=0)

Example

Let’s see the following code to get a better understanding −

import pandas as pd
time_series = pd.date_range('01-01-2020', periods = 5, freq ='12H')
df = pd.DataFrame({"Id":[1, 2, 3, 4, 5],
                     "Age":[10, 12, 14, 11, 13]},
                        index = time_series)
print("Dataframe is:\n",df)
print("shift the index by three periods in positive direction")
print(df.shift(2,axis=0))
print("shift the index by three periods in negative direction")
print(df.shift(-2,axis=0))

Output

Dataframe is:
                   Id Age
2020-01-01 00:00:00 1 10
2020-01-01 12:00:00 2 12
2020-01-02 00:00:00 3 14
2020-01-02 12:00:00 4 11
2020-01-03 00:00:00 5 13
shift the index by three periods in positive direction
                     Id Age
2020-01-01 00:00:00 NaN NaN
2020-01-01 12:00:00 NaN NaN
2020-01-02 00:00:00 1.0 10.0
2020-01-02 12:00:00 2.0 12.0
2020-01-03 00:00:00 3.0 14.0
shift the index by three periods in negative direction
                     Id Age
2020-01-01 00:00:00 3.0 14.0
2020-01-01 12:00:00 4.0 11.0
2020-01-02 00:00:00 5.0 13.0
2020-01-02 12:00:00 NaN NaN
2020-01-03 00:00:00 NaN NaN

Updated on: 25-Feb-2021

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements