Sub topic 3
Shifting, Differencing, and Rolling Windows
Assume you know how to create pandas Series and DataFrames, select columns, and filter rows. A time series should use a sorted DatetimeIndex for time-based operations.
Shifting, differencing, and rolling windows
shift() moves values without moving their index. diff() subtracts each value from the previous value. A rolling window calculates a statistic over nearby observations.
import pandas as pd
idx = pd.to_datetime([
"2024-03-01 09:00",
"2024-03-01 12:00",
"2024-03-02 10:00",
])
sales = pd.Series([10, 15, 12], index=idx).sort_index()
print(sales.shift(1))
print(sales.diff())
print(sales.rolling("1D").mean())A time-based window such as "1D" uses elapsed time. It does not mean “one row.” The first result is often missing because there is no earlier value.
Resampling to regular intervals
resample() groups timestamped data into calendar intervals. It is useful when observations arrive irregularly.
daily_sales = sales.resample("D").sum()
print(daily_sales)The "D" rule means calendar day. Other common rules include "h" for hour, "W" for week, and "MS" for month start.
Working with time zones
A naive timestamp has no time-zone information. tz_localize() assigns a zone without changing the displayed clock time. tz_convert() changes the displayed time to represent the same instant elsewhere.
times = pd.to_datetime(["2024-03-10 12:00", "2024-03-10 13:00"])
utc_times = times.tz_localize("UTC")
new_york_times = utc_times.tz_convert("America/New_York")
print(new_york_times)Periods and PeriodIndex for calendar spans
A Period represents a span such as a month, rather than one instant.
period = pd.Period("2024-03", freq="M")
print(period.start_time)
print(period.end_time)
monthly = sales.to_period("M").groupby(level=0).sum()
print(monthly)Common pitfalls and how to debug them
- Sort a
DatetimeIndexbefore slicing, rolling, or resampling. - Parse ambiguous dates explicitly. Decide whether
"03/04/2024"means March 4 or April 3. - Use
errors="coerce"to turn invalid text intoNaT, pandas’ missing-time value. Check with.isna(). - Localize naive times only when you know which zone those clock readings use.
- Avoid mixing naive and time-zone-aware timestamps.
Exercise
Which method should you use to convert UTC timestamps to a local time zone?
Show answer
Use tz_convert() after the timestamps have a time zone, such as UTC.