w3resource

Creating Custom Resampling periods

Pandas Resampling and Frequency Conversion: Exercise-14 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/python-exercises/pandas/resampling-frequency-conversion/creating-custom-resampling-periods-in-pandas.php