Downsampling Time Series Data from Minute to Hourly Frequency
Pandas Resampling and Frequency Conversion: Exercise-5 with Solution
Write a Pandas program to downsample Time Series data from Minute to Hourly Frequency.
Sample Solution:
Python Code :
# Import necessary libraries
import pandas as pd
import numpy as np
# Create a time series data with minute frequency
date_rng = pd.date_range(start='2023-01-01', end='2023-01-01 23:59', freq='T')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)
# Downsample the time series to hourly frequency
ts_hourly = ts.resample('H').sum()
# Display the downsampled time series
print(ts_hourly)
Output:
2023-01-01 00:00:00 -9.638825 2023-01-01 01:00:00 12.406546 2023-01-01 02:00:00 -2.037772 2023-01-01 03:00:00 -5.785124 2023-01-01 04:00:00 -0.468874 2023-01-01 05:00:00 10.961871 2023-01-01 06:00:00 14.265901 2023-01-01 07:00:00 -5.936786 2023-01-01 08:00:00 -5.200742 2023-01-01 09:00:00 -0.832787 2023-01-01 10:00:00 -4.936277 2023-01-01 11:00:00 1.323612 2023-01-01 12:00:00 3.284874 2023-01-01 13:00:00 7.342899 2023-01-01 14:00:00 -3.245981 2023-01-01 15:00:00 -7.716751 2023-01-01 16:00:00 -5.579430 2023-01-01 17:00:00 1.763545 2023-01-01 18:00:00 3.903313 2023-01-01 19:00:00 -0.630663 2023-01-01 20:00:00 5.425722 2023-01-01 21:00:00 -2.147499 2023-01-01 22:00:00 3.667550 2023-01-01 23:00:00 2.219400 Freq: H, dtype: float64
Explanation:
- Import Pandas and NumPy libraries.
- Create a date range with minute frequency.
- Generate a random time series data with the created date range.
- Downsample the time series data to hourly frequency by summing the values.
- Print the downsampled 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 Weekly Frequency.
Next: Resampling Time Series data to Business day Frequency.
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/downsampling-time-series-data-from-minute-to-hourly-frequency.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics