w3resource

Resampling Time Series data to Quarterly Frequency


9. Resample Time Series Data to Quarterly Frequency

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

Sample Solution:

Python Code :

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

# Create a time series data with monthly frequency
date_rng = pd.date_range(start='2019-01-01', end='2019-12-01', freq='M')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)

# Resample the time series to quarterly frequency
ts_quarterly = ts.resample('Q').mean()

# Display the resampled time series
print(ts_quarterly)

Output:

2019-03-31    0.045935
2019-06-30   -1.032537
2019-09-30    0.062271
2019-12-31    1.227764
Freq: Q-DEC, dtype: float64

Explanation:

  • Import Pandas and NumPy libraries.
  • Create a date range with monthly frequency.
  • Generate a random time series data with the created date range.
  • Resample the time series data to quarterly frequency by calculating the mean.
  • Print the resampled time series data.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to resample monthly data to quarterly frequency and compute the sum for each quarter.
  • Write a Pandas program to resample daily time series data to quarterly frequency using the last available observation.
  • Write a Pandas program to resample time series data to quarterly frequency and calculate the average quarterly growth rate.
  • Write a Pandas program to resample a financial dataset to quarterly frequency and compute the quarterly volatility.

Python Code Editor:

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

Previous: Resampling Time Series data with Custom functions.
Next: Resampling Time Series data to Yearly 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.