Resampling Time Series data with Custom functions
Pandas Resampling and Frequency Conversion: Exercise-8 with Solution
Write a Pandas program to resample Time Series data with custom functions.
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)
# Define a custom function for resampling
def custom_resample(array):
return np.sum(array) / len(array)
# Resample the time series to daily frequency using the custom function
ts_custom = ts.resample('D').apply(custom_resample)
# Display the resampled time series
print(ts_custom)
Output:
2023-01-01 0.147705 2023-01-02 -0.022656 2023-01-03 -0.131713 2023-01-04 0.053327 2023-01-05 0.562042 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.
- Define a custom function for resampling.
- Resample the time series data to daily frequency using the custom function.
- Print the resampled time series data.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Interpolating Missing values after Resampling.
Next: Resampling Time Series data to Quarterly 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/resampling-time-series-data-with-custom-functions.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics