w3resource

Resampling Time Series data to Weekly Frequency


4. Resample Time Series Data to Weekly Frequency

Write a Pandas program to resample Time Series data to Weekly frequency.

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='2021-01-01', end='2021-02-01', freq='D')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)

# Resample the time series to weekly frequency
ts_weekly = ts.resample('W').mean()

# Display the resampled time series
print(ts_weekly)

Output:

2021-01-03    1.000809
2021-01-10    0.107989
2021-01-17   -0.030971
2021-01-24   -0.224898
2021-01-31   -0.701690
2021-02-07   -0.578448
Freq: W-SUN, 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.
  • Resample the time series data to weekly frequency by calculating the mean.
  • Print the resampled time series data.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to resample hourly data to a weekly frequency and compute the weekly average temperature.
  • Write a Pandas program to resample minute-level data to weekly frequency and count the number of events per week.
  • Write a Pandas program to resample a time series to weekly frequency and forward-fill any missing weekly records.
  • Write a Pandas program to resample daily data to weekly frequency and calculate the weekly sum for a financial time series.

Python Code Editor:

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

Previous: Upsampling Time Series data from daily to Hourly Frequency.
Next: Downsampling Time Series Data from Minute to Hourly Frequency.

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.