Function Syntax
The function has a syntax as shown in the code snippet below:
Function Parameters
The function parameters are as:
- periods – defines the number of increments by which the value is shifted. This can be a positive or negative integer.
- 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.
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:
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:
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.