Skip to content

temporal_context_features

temporal_context_features

temporal_context_features(panel: DataFrame, *, time_col: str = 'fetched_at', holidays: Any = None) -> DataFrame

Add standard calendar context columns for descriptive temporal analysis.

Every descriptive model or test on bike-share data needs to isolate peaks, weekends and holidays. This adds them once, consistently, from a tz-aware timestamp, so each study does not re-derive error-prone dt.dayofweek and pd.cut rules (and the UTC-versus-local traps that come with them). Convert to local time first for local-calendar semantics.

Parameters:

Name Type Description Default
panel DataFrame

Any frame with a tz-aware datetime in time_col (a column or a MultiIndex level).

required
time_col str

The timestamp to derive context from.

"fetched_at"
holidays optional

A collection of dates (anything to_datetime accepts). When given, an is_holiday boolean column is added; omitted otherwise (no silent assumption).

None

Returns:

Type Description
DataFrame

A copy of panel with is_weekend (boolean), time_block (ordered Categorical of TIME_BLOCKS) and, when holidays is given, is_holiday (boolean).

See Also

cyclical_time_features : Smooth sin/cos calendar encodings. join_exogenous_timeseries : Attach an external series (weather).

Examples:

>>> import pandas as pd
>>> from gbfs_toolkit import temporal_context_features
>>> df = pd.DataFrame({"fetched_at": pd.to_datetime(
...     ["2026-06-27 08:30", "2026-06-29 23:00"], utc=True)})
>>> out = temporal_context_features(df)
>>> list(out["time_block"])
['am_peak', 'evening']
>>> out["is_weekend"].tolist()
[True, False]
Source code in src/gbfs_toolkit/analytics/temporal.py
def temporal_context_features(
    panel: pd.DataFrame, *, time_col: str = "fetched_at", holidays: Any = None
) -> pd.DataFrame:
    """Add standard calendar context columns for descriptive temporal analysis.

    Every descriptive model or test on bike-share data needs to isolate peaks, weekends and
    holidays. This adds them once, consistently, from a tz-aware timestamp, so each study does not
    re-derive error-prone ``dt.dayofweek`` and ``pd.cut`` rules (and the UTC-versus-local traps
    that come with them). Convert to local time first for local-calendar semantics.

    Parameters
    ----------
    panel : pandas.DataFrame
        Any frame with a tz-aware datetime in ``time_col`` (a column or a MultiIndex level).
    time_col : str, default "fetched_at"
        The timestamp to derive context from.
    holidays : optional
        A collection of dates (anything `to_datetime` accepts). When given, an
        ``is_holiday`` boolean column is added; omitted otherwise (no silent assumption).

    Returns
    -------
    pandas.DataFrame
        A copy of ``panel`` with ``is_weekend`` (boolean), ``time_block`` (ordered Categorical of
        `TIME_BLOCKS`) and, when ``holidays`` is given, ``is_holiday`` (boolean).

    See Also
    --------
    [`cyclical_time_features`][gbfs_toolkit.cyclical_time_features] : Smooth sin/cos calendar encodings.
    [`join_exogenous_timeseries`][gbfs_toolkit.join_exogenous_timeseries] : Attach an external series (weather).

    Examples
    --------
    >>> import pandas as pd
    >>> from gbfs_toolkit import temporal_context_features
    >>> df = pd.DataFrame({"fetched_at": pd.to_datetime(
    ...     ["2026-06-27 08:30", "2026-06-29 23:00"], utc=True)})
    >>> out = temporal_context_features(df)
    >>> list(out["time_block"])
    ['am_peak', 'evening']
    >>> out["is_weekend"].tolist()
    [True, False]
    """
    out = panel.copy()
    ts = _time_values(out, time_col)
    hour = ts.hour
    block = np.select(
        [hour < 7, hour < 10, hour < 16, hour < 19],
        ["night", "am_peak", "midday", "pm_peak"],
        default="evening",
    )
    out["is_weekend"] = pd.array(ts.dayofweek >= 5, dtype="boolean")
    out["time_block"] = pd.Categorical(block, categories=TIME_BLOCKS, ordered=True)
    if holidays is not None:
        hol = set(pd.DatetimeIndex(pd.to_datetime(list(holidays))).normalize())
        out["is_holiday"] = pd.array(pd.DatetimeIndex(ts.normalize()).isin(hol), dtype="boolean")
    return out