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

Syntax

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

DataFrame.shift(
    periods=1, 
    freq=None, 
    axis=0, 
    fill_value=NoDefault.no_default
    )

Parameter(s)

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 = {
    'One':[10,20,30,40],
    'Two':[50,60,70,80],
    'Three':[90,100,110,120],
    'Four':[130,140,150,160]
}

# 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)

Output

The output of the above program is:

Example: pandas.DataFrame.shift() Method

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.