w3resource

Shifting Time Series data Forward and Backward

Pandas Resampling and Frequency Conversion: Exercise-11 with Solution

Write a Pandas program to shift Time Series Data Forward and Backward.

Sample Solution:

Python Code :

# Import necessary libraries
import pandas as pd
import numpy as np

# Create a time series data with daily frequency
date_rng = pd.date_range(start='2018-01-01', end='2018-01-10', freq='D')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)

# Shift the time series data forward by 2 days
ts_shifted_forward = ts.shift(2)

# Shift the time series data backward by 2 days
ts_shifted_backward = ts.shift(-2)

# Display the shifted time series data
print("Shifted Forward:\n", ts_shifted_forward)
print("Shifted Backward:\n", ts_shifted_backward)

Output:

Shifted Forward:
 2018-01-01         NaN
2018-01-02         NaN
2018-01-03   -0.089532
2018-01-04   -0.603577
2018-01-05    0.028048
2018-01-06    0.306228
2018-01-07    0.639217
2018-01-08   -0.583604
2018-01-09    1.492077
2018-01-10    0.660660
Freq: D, dtype: float64
Shifted Backward:
 2018-01-01    0.028048
2018-01-02    0.306228
2018-01-03    0.639217
2018-01-04   -0.583604
2018-01-05    1.492077
2018-01-06    0.660660
2018-01-07   -0.155463
2018-01-08   -1.124159
2018-01-09         NaN
2018-01-10         NaN
Freq: D, dtype: float64

Explanation:

  • Import Pandas and NumPy libraries.
  • Create a date range with daily frequency.
  • Generate a random time series data with the created date range.
  • Shift the time series data forward by 2 days.
  • Shift the time series data backward by 2 days.
  • Print the shifted time series data for both forward and backward shifts.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Resampling Time Series data to Yearly Frequency.
Next: Calculating Rolling Mean of Resampled data.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.