Resampling time series in Data Analysis Python - 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 it takes to resample grows as the data size grows.
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)
resampled = data.resample('H').mean()
This code creates a time series with 1000 minute-level points and resamples it to hourly data by averaging.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Grouping data points by hour and computing the mean for each group.
- How many times: The number of groups depends on input size; roughly one group per hour in the data.
As the number of data points grows, the number of groups grows proportionally, and each group's mean is computed.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 group, 10 operations |
| 100 | About 1-2 groups, 100 operations |
| 1000 | About 16 groups, 1000 operations |
Pattern observation: Operations grow roughly in direct proportion to the number of data points.
Time Complexity: O(n)
This means the time to resample grows linearly as the number of data points increases.
[X] Wrong: "Resampling time is constant no matter how much data there is."
[OK] Correct: More data means more groups and more calculations, so time grows with data size.
Understanding how resampling scales helps you handle real-world time series data efficiently and shows you can think about performance.
"What if we resampled to a daily frequency instead of hourly? How would the time complexity change?"
Practice
Solution
Step 1: Understand the meaning of resampling
Resampling means changing how often data points appear in time, like from daily to monthly.Step 2: Compare options to definition
Only Changing the time frequency of the data correctly describes changing the time frequency of data.Final Answer:
Changing the time frequency of the data -> Option CQuick Check:
Resampling = Changing frequency [OK]
- Thinking resampling sorts data
- Confusing resampling with cleaning data
- Believing resampling changes data type
df to monthly frequency and take the mean?Solution
Step 1: Identify the correct frequency string
Pandas uses 'M' for monthly frequency, not 'monthly' or 'month'.Step 2: Check aggregation function name
The correct function ismean(), notaverage().Final Answer:
df.resample('M').mean() -> Option DQuick Check:
Use 'M' and mean() for monthly average [OK]
- Using 'monthly' or 'month' instead of 'M'
- Using average() instead of mean()
- Missing parentheses after mean
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()
print(resampled)Solution
Step 1: Understand the original data and frequency
Data has values 10,20,30,40 on consecutive days from 2023-01-01 to 2023-01-04.Step 2: Resample with '2D' and sum
Resampling groups every 2 days: (Jan 1+2) and (Jan 3+4). Sums are 10+20=30 and 30+40=70.Final Answer:
2023-01-01 30 2023-01-03 70 -> Option AQuick Check:
Sum every 2 days = 30, 70 [OK]
- Summing only one day instead of two
- Confusing sum with mean
- Misreading the date index
df = pd.DataFrame({'value': [1, 2, 3]}, index=pd.date_range('2023-01-01', periods=3))
resampled = df.resample('W').meanSolution
Step 1: Check the resample syntax
The code usesmeanwithout parentheses, so it returns a method, not the result.Step 2: Verify frequency and index
'W' is correct for weekly, and the index is a datetime index, so no issues there.Final Answer:
Missing parentheses after 'mean' function call -> Option AQuick Check:
Call mean() with () to get result [OK]
- Forgetting parentheses on aggregation functions
- Thinking 'W' is invalid frequency
- Not setting datetime index before resampling
df indexed by datetime. You want to resample it to hourly data but only keep hours where the average temperature is above 20°C. Which code snippet correctly does this?Solution
Step 1: Resample to hourly and calculate mean
Usedf.resample('H').mean()to get hourly averages.Step 2: Filter rows where temperature > 20
Using.query('temperature > 20')filters rows correctly by the 'temperature' column.Final Answer:
df.resample('H').mean().query('temperature > 20') -> Option BQuick Check:
Use query() to filter by column condition [OK]
- Applying boolean filter on DataFrame without column name
- Using filter() incorrectly for row filtering
- Repeating resample twice causing inefficiency
Ready to prove it?
Pass the test and this pattern moves unknown
