Resampling time series data in Pandas - Time & Space Complexity
When working with time series data, resampling helps us change the frequency of data points.
We want to know how the time to resample grows as the data size increases.
Analyze the time complexity of the following code snippet.
import pandas as pd
dates = pd.date_range('2023-01-01', periods=1000, freq='T')
data = pd.Series(range(1000), index=dates)
# Resample data to 10-minute frequency and take the mean
resampled = data.resample('10T').mean()
This code changes data from 1-minute intervals to 10-minute intervals by averaging values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Grouping data points into new time bins and computing the mean for each group.
- How many times: Once for each new time bin created by resampling.
As the number of data points grows, the number of groups also grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 group operation |
| 100 | About 10 group operations |
| 1000 | About 100 group operations |
Pattern observation: The work grows roughly in proportion to the number of groups.
Time Complexity: O(n)
This means the time to resample grows linearly with the number of data points.
[X] Wrong: "Resampling time is constant no matter how much data there is."
[OK] Correct: More data means more groups and calculations, so time grows with data size.
Understanding how resampling scales helps you work efficiently with time series data in real projects.
"What if we changed the aggregation from mean to a custom function that is slower? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of resampling
Resampling changes how often data points appear in time, either by grouping or expanding.Step 2: Identify what resampling affects
It changes the time frequency, not sorting or file formats.Final Answer:
Change the time frequency of the data to summarize or expand it -> Option CQuick Check:
Resampling = Change frequency [OK]
- Confusing resampling with sorting data
- Thinking resampling removes missing values automatically
- Believing resampling changes file formats
df with a datetime index to monthly frequency and calculate the mean?Solution
Step 1: Identify the correct resample frequency for monthly data
'M' stands for month-end frequency in pandas resampling.Step 2: Choose the correct aggregation function
To calculate the mean after downsampling, use.mean().Final Answer:
df.resample('M').mean() -> Option AQuick Check:
Monthly mean = df.resample('M').mean() [OK]
- Using 'D' instead of 'M' for monthly frequency
- Using sum() when mean() is asked
- Calling fillna() without upsampling
print(resampled)?
import pandas as pd
idx = pd.date_range('2023-01-01', periods=4, freq='D')
data = [10, 20, 30, 40]
df = pd.DataFrame({'value': data}, index=idx)
resampled = df.resample('2D').sum()Solution
Step 1: Understand resampling with '2D' and sum aggregation
Resampling with '2D' groups data every 2 days and sums values in each group.Step 2: Calculate sums for each 2-day period
First period: 2023-01-01 + 2023-01-02 = 10 + 20 = 30; Second period: 2023-01-03 + 2023-01-04 = 30 + 40 = 70.Final Answer:
value 2023-01-01 30 2023-01-03 70 -> Option AQuick Check:
Sum every 2 days = 30, 70 [OK]
- Confusing sum with mean aggregation
- Expecting original daily data instead of grouped
- Misreading the index labels after resampling
df = pd.DataFrame({'value': [1, 2]}, index=pd.date_range('2023-01-01', periods=2, freq='D'))
upsampled = df.resample('H').mean()Solution
Step 1: Identify the effect of upsampling daily to hourly
Upsampling creates new rows for each hour, but original data has only daily points.Step 2: Recognize missing values after upsampling
New hourly rows have no data, so mean() returns NaN unless filled.Final Answer:
Upsampling without filling missing values results in NaNs -> Option BQuick Check:
Upsampling needs fillna() to avoid NaNs [OK]
- Thinking 'H' frequency is invalid
- Believing mean() cannot be used after resampling
- Ignoring datetime index requirement
df with a datetime index. You want to create a new DataFrame with hourly average temperatures but only for hours where at least 45 minutes of data exist. Which approach correctly achieves this?Solution
Step 1: Understand the requirement for minimum data points per hour
We want hourly averages only if 45 or more minutes of data exist (i.e., at least 45 rows per hour).Step 2: Use a custom function with resample and apply
Usingapplywith a lambda checks the length of each group and calculates mean only if condition met; else returnsNone.Step 3: Remove hours with insufficient data
Callingdropna()removes hours where the condition failed (null values).Final Answer:
df.resample('H').apply(lambda x: x.mean() if len(x) >= 45 else None).dropna() -> Option DQuick Check:
Custom apply filters groups by size before averaging [OK]
- Using mean() without checking group size
- Using sum() instead of mean() for temperature
- Dropping NaNs without filtering groups first
Ready to prove it?
Pass the test and this pattern moves unknown
