Python - Pandas dataframe.shift() with Example

Learn about the Pandas dataframe.shift(), its working with examples. Submitted by Pranit Sharma, on August 29, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

pandas.DataFrame.shift() Method

It is used to shift index by desired number of periods with an optional time freq. Pandas pandas.DataFrame.shift() method uses an optional time frequency to shift the index by the required number of periods passed inside it. Here, periods refer to a parameter called the period, which represents the number of shifts that have to be made. This function is very helpful when dealing with time-series data. source


The syntax of pandas.DataFrame.shift() method is:



The parameter(s) of pandas.DataFrame.shift() method are:

  • periods: Number of periods (intervals) to move.
  • freq: timedelta or time string values to use from the time series module.
  • axis: if 0 is passed, it means shifting row-wise, if 1 is passed, it means shifting column-wise.

Return Value

It returns a DataFrame that is a copy of the input object i.e., shifted/Modified DataFrame.

Let us understand with the help of an example,

Python pandas.DataFrame.shift() Method Example

# Importing pandas package
import pandas as pd

# Getting a series of date for index
indices = pd.date_range('10 / 10 / 2000', periods = 4, freq ='24H')

# Creating dictionary
d = {

# Creating DataFrame
df = pd.DataFrame(d,index=indices)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")

# Shifting the DataFrame
result = df.shift(2, axis = 0)

# Display modified DataFrame
print("Modified DataFrame:\n",result)


The output of the above program is:

Example: pandas.DataFrame.shift() Method

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.