JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas DataFrame DataFrame.shift() function

Author:JIYIK Last Updated:2025/04/12 Views:

The Pandas DataFrame.shift method is used to DataFrameshift the index of a by a specified number of periods, with an optional time frequency.


pandas.DataFrame.shift()grammar

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

parameter

periods Integer. Determines the number of cycles to move the index. Can be negative or positive.
freq DateOffset, tseries.offsets, timedeltaor str. Optional parameter used to move index values ​​without adjusting the data
axis Move along rows ( axis=0) or columns ( )axis=1
fill_value Scalar value for newly introduced missing values

Return Value

DataFrameIt returns a object with the shifted index values .


Example code: DataFrame.shift()Function moves along the line

import pandas as pd

df = pd.DataFrame({'X': [1, 2, 3,],
                   'Y': [4, 1, 8]})
print("Original DataFrame:")
print(df)

shifted_df=df.shift(periods=1)
print("Shifted DataFrame")
print(shifted_df)

Output:

Original DataFrame:
   X  Y
0  1  4
1  2  1
2  3  8
Shifted DataFrame
     X    Y
0  NaN  NaN
1  1.0  4.0
2  2.0  1.0

Here, we periodsset the value of to 1, which will DataFramemove the rows of from the top to the bottom 1by units.

As you move toward the bottom, the top row becomes empty and NaNis filled with the default value.

If we want to move the row from the bottom to the top, we can periodsset the parameter to a negative value.

import pandas as pd

df = pd.DataFrame({'X': [1, 2, 3,],
                   'Y': [4, 1, 8]})
print("Original DataFrame:")
print(df)

shifted_df=df.shift(periods=-2)
print("Shifted DataFrame")
print(shifted_df)

Output:

Original DataFrame:
   X  Y
0  1  4
1  2  1
2  3  8
Shifted DataFrame
     X    Y
0  3.0  8.0
1  NaN  NaN
2  NaN  NaN

It moves the rows from bottom to top with a period of 2.


Example code: DataFrame.shift()Function moves along columns

If we want to move along the column axis, we shift()set that in the method axis=1.

import pandas as pd

df = pd.DataFrame({'X': [1, 2, 3,],
                   'Y': [4, 1, 8]})
print("Original DataFrame:")
print(df)
shifted_df=df.shift(periods=1,axis=1)
print("Shifted DataFrame")
print(shifted_df)

Output:

Original DataFrame:
   X  Y
0  1  4
1  2  1
2  3  8
Shifted DataFrame
    X    Y
0 NaN  1.0
1 NaN  2.0
2 NaN  3.0

Here, we periodsset the value of to 1, which will DataFrameshift the column axis of from left to right 1by units.

If we want to move the column axis from right to left, we periodsset a negative value for the parameter.

import pandas as pd

df = pd.DataFrame({'X': [1, 2, 3,],
                   'Y': [4, 1, 8]})
print("Original DataFrame:")
print(df)

shifted_df=df.shift(periods=-1,axis=1)
print("Shifted DataFrame")
print(shifted_df)

Output:

Original DataFrame:
   X  Y
0  1  4
1  2  1
2  3  8
Shifted DataFrame
     X   Y
0  4.0 NaN
1  1.0 NaN
2  8.0 NaN

It shifts the column axis from right to left 1by periods.


Example code: DataFrame.shiftmethod with parametersfill_value

In the previous example, the missing values ​​after shifting are filled by default , but we can also fill them with other values ​​instead of NaNby using the parameter . We can also fill the missing values ​​with other values ​​instead of by using the parameter .fill_valueNaNfill_valueNaN

import pandas as pd

df = pd.DataFrame({'X': [1, 2, 3,],
                   'Y': [4, 1, 8]})
print("Original DataFrame:")
print(df)

shifted_df=df.shift(periods=-1,
                    axis=1,
                    fill_value=4)
print("Shifted DataFrame")
print(shifted_df)

Output:

Original DataFrame:
   X  Y
0  1  4
1  2  1
2  3  8
Shifted DataFrame
   X  Y
0  4  4
1  1  4
2  8  4

It fills all shift()missing values ​​created by the method with .4

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Finding the installed version of Pandas

Publish Date:2025/04/12 Views:190 Category:Python

Pandas is one of the commonly used Python libraries for data analysis, and Pandas versions need to be updated regularly. Therefore, other Pandas requirements are incompatible. Let's look at ways to determine the Pandas version and dependenc

KeyError in Pandas

Publish Date:2025/04/12 Views:81 Category:Python

This tutorial explores the concept of KeyError in Pandas. What is Pandas KeyError? While working with Pandas, analysts may encounter multiple errors thrown by the code interpreter. These errors are wide ranging and can help us better invest

Grouping and Sorting in Pandas

Publish Date:2025/04/12 Views:90 Category:Python

This tutorial explored the concept of grouping data in a DataFrame and sorting it in Pandas. Grouping and Sorting DataFrame in Pandas As we know, Pandas is an advanced data analysis tool or package extension in Python. Most of the companies

Plotting Line Graph with Data Points in Pandas

Publish Date:2025/04/12 Views:65 Category:Python

Pandas is an open source data analysis library in Python. It provides many built-in methods to perform operations on numerical data. Data visualization is very popular nowadays and is used to quickly analyze data visually. We can visualize

Converting Timedelta to Int in Pandas

Publish Date:2025/04/12 Views:123 Category:Python

This tutorial will discuss converting a to a using dt the attribute in Pandas . timedelta int Use the Pandas dt attribute to timedelta convert int To timedelta convert to an integer value, we can use the property pandas of the library dt .

Pandas fill NaN values

Publish Date:2025/04/12 Views:93 Category:Python

This tutorial explains how we can use DataFrame.fillna() the method to fill NaN values ​​with specified values. We will use the following DataFrame in this article. import numpy as np import pandas as pd roll_no = [ 501 , 502 , 503 , 50

Pandas Convert String to Number

Publish Date:2025/04/12 Views:147 Category:Python

This tutorial explains how to pandas.to_numeric() convert string values ​​of a Pandas DataFrame into numeric type using the method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 , 103 , 343 , 565 ], "Name" :

How to Change the Data Type of a Column in Pandas

Publish Date:2025/04/12 Views:139 Category:Python

We will look at methods for changing the data type of columns in a Pandas Dataframe, as well as options like to_numaric , , as_type and infer_objects . We will also discuss how to to_numaric use downcasting the option in . to_numeric Method

Get the first row of Dataframe Pandas

Publish Date:2025/04/12 Views:78 Category:Python

This tutorial explains how to use the get_first_row pandas.DataFrame.iloc attribute and pandas.DataFrame.head() get_first_row method from a Pandas DataFrame. We will use the following DataFrame in the following example to explain how to get

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial