w3resource

Resampling Time Series data to Weekly Frequency

Pandas Resampling and Frequency Conversion: Exercise-4 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/resampling-frequency-conversion/resampling-time-series-data-to-weekly-frequency-with-pandas.php