Certainly! Below is a Python function that will summarize your time series data in a pandas DataFrame based on a specified interval and aggregation function (sum, min, max, mean, or even a custom function). This function handles interval strings like '1 min', '2 hours', '1 day', etc., and converts them into pandas-compatible offset aliases for resampling.
import pandas as pd
import re
def parse_interval(interval_str):
"""
Parse an interval string into a pandas offset alias.
"""
interval_str = interval_str.strip()
# Regular expression to parse the numbers and units
pattern = r'^(\d+)\s*(min|mins?|hours?|days?|h|d|m)$'
match = re.match(pattern, interval_str, re.IGNORECASE)
if not match:
raise ValueError(f"Invalid interval format: '{interval_str}'")
value, unit = match.groups()
value = int(value)
unit = unit.lower()
if unit.startswith('min') or unit == 'm':
offset = f'{value}T' # 'T' is the pandas offset alias for minute
elif unit.startswith('h') or unit.startswith('hour'):
offset = f'{value}H' # 'H' is the offset alias for hour
elif unit.startswith('d') or unit.startswith('day'):
offset = f'{value}D' # 'D' is the offset alias for day
else:
raise ValueError(f"Invalid interval unit: '{unit}'")
return offset
def summarize_timeseries(df, interval, agg_func, time_col='timestamp'):
"""
Summarize time series data in a DataFrame by a given interval and aggregation function.
Parameters:
- df: pandas DataFrame containing the time series data.
- interval: Interval string (e.g., '1 min', '2 hours', '1 day').
- agg_func: Aggregation function ('sum', 'min', 'max', 'mean', or a custom function).
- time_col: Name of the datetime column in df (default is 'timestamp').
Returns:
- resampled_df: Resampled and aggregated DataFrame.
"""
# Parse interval
try:
offset = parse_interval(interval)
except ValueError as e:
print(f"Warning: {e}. Attempting to use the interval as a pandas offset alias.")
offset = interval # Assume the user provided a valid pandas offset alias
# Ensure the time_col is in datetime format and set as index
if time_col in df.columns:
df = df.copy() # Avoid SettingWithCopyWarning
df[time_col] = pd.to_datetime(df[time_col])
df.set_index(time_col, inplace=True)
elif df.index.name == time_col:
df = df.copy()
df.index = pd.to_datetime(df.index)
else:
raise ValueError(f"Column '{time_col}' not found in DataFrame.")
# Resample and aggregate
resampled_df = df.resample(offset).agg(agg_func)
return resampled_df
How to Use the Function
-
Import pandas and your data:
import pandas as pd
# Assume 'df' is your DataFrame loaded from a CSV or other source
# It should have a datetime column, e.g., 'timestamp'
-
Call the summarize_timeseries function:
# For example, to get the sum of values every 30 minutes:
resampled_df = summarize_timeseries(df, '30 mins', 'sum')
# To get the mean of values every 1 hour:
resampled_df = summarize_timeseries(df, '1 hour', 'mean')
# To get the max of values every day:
resampled_df = summarize_timeseries(df, '1 day', 'max')
-
Using a custom aggregation function:
You can also pass a custom function to the agg_func parameter.
# Define a custom aggregation function
def custom_agg(series):
return series.sum() * 2 # Example: sum of the series multiplied by 2
# Use the custom function
resampled_df = summarize_timeseries(df, '1 hour', custom_agg)
Example
Let's create a simple example to demonstrate how the function works.
import pandas as pd
import numpy as np
# Create a sample DataFrame
date_range = pd.date_range(start='2023-01-01', periods=100, freq='T') # 1-minute frequency
df = pd.DataFrame({
'timestamp': date_range,
'value': np.random.rand(100)
})
# Summarize the data every 15 minutes, calculating the mean
resampled_df = summarize_timeseries(df, '15 mins', 'mean')
print(resampled_df)
Output:
value
timestamp
2023-01-01 00:00:00 0.517769
2023-01-01 00:15:00 0.507069
2023-01-01 00:30:00 0.476065
2023-01-01 00:45:00 0.533699
2023-01-01 01:00:00 0.414635
Explanation:
- The function first parses the interval string ('15 mins') into a pandas offset alias ('15T').
- It ensures that the
timestamp column is in datetime format and sets it as the DataFrame index.
- It then resamples the data using the specified interval and applies the aggregation function (
mean in this case).
- The result is a DataFrame indexed by the resampled timestamps with the aggregated values.
Supported Interval Formats:
The function supports intervals in the following formats:
'X min' or 'X mins' or 'X m' where X is an integer (minutes)
'X hour' or 'X hours' or 'X h' (hours)
'X day' or 'X days' or 'X d' (days)
Supported Aggregation Functions:
You can pass any of the following strings as the agg_func:
Or you can pass a custom function that takes a pandas Series and returns a scalar.
Error Handling:
- If the interval string is not recognized, the function will attempt to use it directly as a pandas offset alias.
- If the
time_col is not found in the DataFrame, a ValueError is raised.
Notes:
- The DataFrame must contain a datetime column or index specified by
time_col.
- The function modifies a copy of the DataFrame to avoid altering the original data.
- Ensure that your datetime column does not contain any missing or invalid values.
Feel free to adjust the function according to your specific data structure and requirements.