﻿ Creating Custom Resampling periods in Pandas

# 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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿