Resampling Time Series data to Yearly Frequency
Pandas Resampling and Frequency Conversion: Exercise-10 with Solution
Write a Pandas program to resample Time Series Data to Yearly 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='2017-01-01', end='2022-01-01', freq='M')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)
# Resample the time series to yearly frequency
ts_yearly = ts.resample('Y').mean()
# Display the resampled time series
print(ts_yearly)
Output:
2017-12-31 0.145795 2018-12-31 -0.212915 2019-12-31 0.327427 2020-12-31 0.027618 2021-12-31 -0.250738 Freq: A-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 yearly 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: Resampling Time Series data to Quarterly Frequency.
Next: Shifting Time Series data Forward and Backward.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-yearly-frequency-with-pandas.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics