Resampling Time Series data with different Aggregation methods
Pandas Resampling and Frequency Conversion: Exercise-3 with Solution
Write a Pandas program to resample Time Series Data with different Aggregation methods.
Sample Solution:
Python Code :
# Import necessary libraries
import pandas as pd
import numpy as np
# Create a time series data with hourly frequency
date_rng = pd.date_range(start='2023-01-01', end='2023-01-05', freq='H')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)
# Resample the time series to daily frequency using different aggregation methods
ts_daily_mean = ts.resample('D').mean()
ts_daily_sum = ts.resample('D').sum()
ts_daily_max = ts.resample('D').max()
# Display the resampled time series
print("Daily Mean:\n", ts_daily_mean)
print("Daily Sum:\n", ts_daily_sum)
print("Daily Max:\n", ts_daily_max)
Output:
Daily Mean: 2023-01-01 0.224578 2023-01-02 -0.077165 2023-01-03 0.052121 2023-01-04 -0.005321 2023-01-05 -0.192389 Freq: D, dtype: float64 Daily Sum: 2023-01-01 5.389876 2023-01-02 -1.851952 2023-01-03 1.250895 2023-01-04 -0.127700 2023-01-05 -0.192389 Freq: D, dtype: float64 Daily Max: 2023-01-01 3.698549 2023-01-02 1.527495 2023-01-03 3.101162 2023-01-04 1.254722 2023-01-05 -0.192389 Freq: D, dtype: float64
Explanation:
- Import Pandas and NumPy libraries.
- Create a date range with hourly frequency.
- Generate a random time series data with the created date range.
- Resample the time series data to daily frequency using mean, sum, and max aggregation methods.
- Print the resampled time series data for each aggregation method.
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: Resampling Time Series data to Weekly Frequency.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics