Chapter 2 · Section 7 practice
Dates, Lags, and Changes over Time
Work from question 1 to 10. Edit your Python box, click Run Code, review the result, then click Submit attempt. Reference answers unlock after all ten attempts are submitted. This records completion, not correctness. Each box runs independently. Progress is saved in this browser.
1. Parse date text
Warm-up. Convert Date to datetime and print the month numbers as a list.
Write your answer, then run it.
2. Chronological order
Warm-up. Set Date as the index, sort it, and print Sales values in chronological order.
Write your answer, then run it.
3. Inclusive date range
Warm-up. Print values from November 2 through November 4 inclusive.
Write your answer, then run it.
4. Weekday numbers
Build your skills. Print weekday numbers for Sunday 2026-11-01 and Monday 2026-11-02.
Write your answer, then run it.
5. Aggregate two orders
Build your skills. Aggregate revenue into daily totals and print them as a list.
Write your answer, then run it.
6. Previous observations
Build your skills. Print the previous values generated by shift(1).
Write your answer, then run it.
7. Absolute change
Build your skills. Print changes from the previous observation.
Write your answer, then run it.
8. Percentage change
Challenge. Print fractional changes multiplied by 100.
Write your answer, then run it.
9. A partial-month summary
Challenge. Print the total for the seven observed November days, then their mean rounded to two decimals.
Write your answer, then run it.
10. Avoid a zero denominator
Challenge. Calculate growth only when previous Sales > 0 and print the rounded list.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Parse date text
import pandas as pd
df = pd.DataFrame({"Date": ["2026-11-01", "2026-12-01"]})
df["Date"] = pd.to_datetime(df["Date"])
print(list(df["Date"].dt.month))Expected output
[11, 12]Parsing enables date-specific attributes.
2. Chronological order
import pandas as pd
df = pd.DataFrame({"Date": ["2026-11-03", "2026-11-01", "2026-11-02"], "Sales": [0, 240, 220]})
df["Date"] = pd.to_datetime(df["Date"])
dated = df.set_index("Date").sort_index()
print(list(dated["Sales"]))Expected output
[240, 220, 0]The input row order is not necessarily chronological.
3. Inclusive date range
import pandas as pd
daily = pd.Series([240, 220, 0, 180, 300, 90, 200],
index=pd.date_range("2026-11-01", periods=7, freq="D"), name="Sales")
print(list(daily.loc["2026-11-02":"2026-11-04"]))Expected output
[220, 0, 180]Both dates are included in this label slice.
4. Weekday numbers
import pandas as pd
dates = pd.Series(pd.to_datetime(["2026-11-01", "2026-11-02"]))
print(list(dates.dt.dayofweek))Expected output
[6, 0]Monday is 0 and Sunday is 6.
5. Aggregate two orders
import pandas as pd
df = pd.DataFrame(
{
"Date": pd.to_datetime(["2026-11-01", "2026-11-01", "2026-11-02"]),
"Revenue": [100, 140, 220],
}
)
dated = df.set_index("Date").sort_index()
print(list(dated["Revenue"].resample("D").sum(min_count=1)))Expected output
[240, 220]Both orders on November 1 contribute to its daily total.
6. Previous observations
import pandas as pd
sales = pd.Series([100.0, 120.0, 90.0])
print(list(sales.shift(1)))Expected output
[nan, 100.0, 120.0]A lag moves values, leaving the first entry without a predecessor.
7. Absolute change
import pandas as pd
sales = pd.Series([100.0, 120.0, 90.0])
print(list(sales - sales.shift(1)))Expected output
[nan, 20.0, -30.0]The change has the same HKD units as sales.
8. Percentage change
import pandas as pd
sales = pd.Series([100.0, 120.0, 90.0])
print(list((sales.pct_change(fill_method=None) * 100).round(2)))Expected output
[nan, 20.0, -25.0]The fractions 0.20 and -0.25 correspond to 20% and -25%.
9. A partial-month summary
import pandas as pd
daily = pd.Series([240, 220, 0, 180, 300, 90, 200],
index=pd.date_range("2026-11-01", periods=7, freq="D"), name="Sales")
monthly = daily.resample("ME").sum(min_count=1)
print(monthly.iloc[0])
print(round(daily.mean(), 2))Expected output
1230
175.71The month-end label does not imply a complete month of observations.
10. Avoid a zero denominator
import pandas as pd
sales = pd.Series([100.0, 0.0, 180.0, 198.0])
previous = sales.shift(1)
denominator = previous.where(previous > 0)
growth = (sales - previous) / denominator
print(list(growth.round(2)))Expected output
[nan, -1.0, nan, 0.1]Growth from zero is undefined; an absolute increase can still be reported.