Chapter 11 worked answers: Dates, Time and Change
On this page
Compare your reasoning after an attempt. Different valid implementations are welcome when they preserve the observation set and the stated meaning.
B2-11-E01 · Respect temporal gaps
Calculate percentage change only where neighbouring observations are consecutive years.
The 2020-to-2022 comparison spans two years and is not labelled as one-year change.
years=pd.Series([2019,2020,2022]);values=pd.Series([10.,12.,18.])
valid=years.diff().eq(1)
change=(100*(values/values.shift()-1)).where(valid)
assert np.isclose(change.iloc[1],20) and pd.isna(change.iloc[2])
print(change)0 NaN
1 20.0
2 NaN
dtype: float64
B2-11-E02 · Keep an unresolved period
Resample daily and preserve an unresolved middle day, not zero.
min_count=1 prevents an empty bin from being interpreted as a measured sum of zero.
s=pd.Series([3.,4.],index=pd.to_datetime(["2023-01-01","2023-01-03"]))
daily=s.resample("D").sum(min_count=1)
assert pd.isna(daily.iloc[1])
print(daily)2023-01-01 3.0
2023-01-02 NaN
2023-01-03 4.0
Freq: D, dtype: float64
B2-11-E03 · Predict a trailing summary
Compute a three-observation trailing mean with complete windows only.
The first two observations lack full windows. A centered window would use later observations.
s=pd.Series([10.,20.,30.,40.])
rolled=s.rolling(3,min_periods=3).mean()
assert rolled.isna().sum()==2 and rolled.iloc[2:].tolist()==[20,30]
print(rolled)0 NaN
1 NaN
2 20.0
3 30.0
dtype: float64
Return to practice
Change one supplied input, predict the effect and rerun your own implementation. Return to the exercise prompts to identify a task you can now explain independently.