Sub topic 2
Choosing Aggregations and Filling Time-Series Gaps
Assume you know basic pandas Series and DataFrame operations, indexing, and Python dates. This chapter focuses on choosing an aggregation when reducing frequency and filling rows when increasing frequency.
Choosing aggregations
When downsampling, resample() creates time bins. An aggregation reduces the rows in each bin to a result.
Common choices include:
sum()for totals, such as daily sales summed by month.mean()for averages, such as average temperature.min()andmax()for ranges.first()andlast()for the first or last observation.ohlc()for financial-style open, high, low, and close values.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="D")
prices = pd.Series([10, 12, 9, 14, 13, 15, 11, 16, 17, 14], index=idx)
weekly_ohlc = prices.resample("W").ohlc()
print(weekly_ohlc)
data = pd.DataFrame(
{"price": prices, "volume": [100] * 10},
index=idx,
)
weekly = data.resample("W").agg({
"price": "mean",
"volume": "sum",
})
print(weekly)ohlc() returns one column for each statistic. With agg(), you choose a different operation for each column. This matters because prices are usually averaged or summarized with OHLC, while volumes are usually summed.
Upsampling: creating a finer time grid
Upsampling creates bins at a higher frequency. The new rows initially contain missing values because no observations existed at those timestamps.
Filling new rows
Use ffill() to carry the last known value forward. Use bfill() to use the next known value backward. Use interpolate() to estimate values between known observations.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=3, freq="W-MON")
values = pd.Series([10.0, 20.0, 30.0], index=idx)
print(values.resample("D").ffill())
print(values.resample("D").bfill())
print(values.resample("D").interpolate())Forward filling fits values that remain valid until replaced. Backward filling is useful when the next observation describes preceding missing rows. Interpolation is appropriate when values change gradually. Avoid filling blindly when missingness has business meaning.
Exercise
Which operation should you use to calculate monthly revenue from daily revenue and monthly average price from daily prices?
Show answer
Use sum() for revenue and mean() for price, or pass both choices through agg().