Python Pandas

Pandas Shift Index

The Pandas shift index function allows you to shift values of datetime-like indexes by a specified number of times.

Function Syntax

The function has a syntax as shown in the code snippet below:

Index.shift(periods=1, freq=None)

Function Parameters

The function parameters are as:

  1. periods – defines the number of increments by which the value is shifted. This can be a positive or negative integer.
  2. freq ­– represents the frequency by which to shift the index. Accepted values include strings such as ‘D’, ‘W’, ‘M’, ‘Y’, etc.

The function returns the shifted index.

Example

Let us start by generating a datetime index in Pandas using the date_range() function. The example below will create a datetime index for the first days of the 12th month of 2022.

import pandas as pd

df = pd.date_range('1/1/2022', periods=12, freq='MS')

df

The resulting index is as shown:

To shift the above index by 5 days, we can run:

print(f"old: {df}")

df = df.shift(5, 'D')

print(f"new: {df}")

The code above should shift each value in the index by five days and return:

You can also perform the shift by a frequency of 1 month as shown:

print(f"old: {df}")

df = df.shift(1, 'M')

print(f"new: {df}")

The above code should return:

Conclusion

This post discusses the usage of the shift() function to shift a specific datetime index by a defined factor.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list