﻿ Resampling Time Series data to Weekly Frequency with Pandas

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿