w3resource

Resampling Time Series data with Custom functions


8. Resample Time Series Data with Custom Functions

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to resample a time series to daily frequency using a custom function that computes the range of values.
  • Write a Pandas program to apply a custom aggregation during resampling that calculates the interquartile range for each period.
  • Write a Pandas program to resample data and apply a lambda function that computes the weighted average for each period.
  • Write a Pandas program to resample a dataset with a custom function that returns both the mean and median for each resampled period.

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.



Follow us on Facebook and Twitter for latest update.