Creating Custom Resampling periods
14. Create Custom Resampling Periods
Write a Pandas program to create custom Resampling periods.
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-10', freq='H')
ts = pd.Series(np.random.randn(len(date_rng)), index=date_rng)
# Define a custom function to resample using Grouper
def custom_resample(ts, freq):
return ts.groupby(pd.Grouper(freq=freq)).mean()
# Resample the time series to a custom period of 2 days
ts_custom = custom_resample(ts, '2D')
# Display the resampled time series
print(ts_custom)
Output:
2023-01-01 0.364041 2023-01-03 -0.162548 2023-01-05 -0.121916 2023-01-07 0.009858 2023-01-09 0.269586 Freq: 2D, 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.
- Define a custom function to resample the time series data using pd.Grouper().
- Use the custom function to resample the time series data to a period of 2 days by calculating the mean.
- Print the resampled time series data.
For more Practice: Solve these Related Problems:
- Write a Pandas program to create custom resampling periods (e.g., 10-day periods) and aggregate data accordingly.
- Write a Pandas program to resample a time series into non-standard periods using a custom date offset.
- Write a Pandas program to define custom resampling intervals and compute the sum for each interval in the dataset.
- Write a Pandas program to create custom resampling periods that overlap and calculate the moving average for each period.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Handling Missing data before Resampling.
Next: Calculating Percentage change in Resampled data.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.