w3resource

Calculating Rolling Mean of Resampled data


Pandas Resampling and Frequency Conversion: Exercise-12 with Solution


Write a Pandas program to calculate Rolling Mean of Resampled Data.

Sample Solution:

Python Code :

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

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

# Resample the time series to daily frequency
ts_daily = ts.resample('D').mean()

# Calculate the rolling mean with a window of 3 days
ts_rolling_mean = ts_daily.rolling(window=3).mean()

# Display the rolling mean of the resampled time series
print(ts_rolling_mean)

Output:

2020-01-01         NaN
2020-01-02         NaN
2020-01-03   -0.021587
2020-01-04    0.040990
2020-01-05    0.079430
2020-01-06    0.013868
2020-01-07    0.116677
2020-01-08    0.067320
2020-01-09   -0.076725
2020-01-10   -0.308754
Freq: D, dtype: float64

Explanation:

  • Import Pandas and NumPy libraries.
  • Create a date range with hourly frequency.
  • Generate a random time series data with the created date range.
  • Resample the time series data to daily frequency by calculating the mean.
  • Calculate the rolling mean of the resampled data with a window of 3 days.
  • Print the rolling mean of the resampled time series data.

Python Code Editor:

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

Previous: Shifting Time Series data Forward and Backward.
Next: Handling Missing data before Resampling .

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.