w3resource

Calculating Rolling Mean of Resampled data


12. Calculate Rolling Mean of Resampled Data

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to resample data to daily frequency and then calculate a 7-day rolling mean.
  • Write a Pandas program to compute a rolling mean on hourly resampled data with a custom window size and adjust for center alignment.
  • Write a Pandas program to calculate a rolling mean of resampled weekly data and visualize the trend over time.
  • Write a Pandas program to resample a time series to monthly frequency and then compute a rolling mean with an expanding window.

Go to:


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

Python Code Editor:

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

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.