Skip to content

diurnal_profiles

diurnal_profiles

diurnal_profiles(panel: DataFrame, *, time_col: str = 'fetched_at', split_weekday: bool = False, min_obs: int = 12) -> tuple[DataFrame, Series]

Build each station's mean occupancy profile by hour of day.

Robust to irregular sampling (aggregates by hour), fills an unobserved hour with the station's own mean. With split_weekday the profile is 48-dim (weekday wd* + weekend we*), capturing commute-vs-leisure rhythms separately.

Returns (profiles, n_obs); profiles indexed by (system_id, station_id) with hour columns, and the per-station observation count.

See Also

cluster_diurnal_profiles : Cluster these profiles into typologies. availability_stats : Scalar per-station statistics.

Examples:

>>> import pandas as pd
>>> idx = pd.date_range("2026-01-01", periods=4, freq="6h", tz="UTC")
>>> panel = pd.DataFrame({
...     "system_id": "s", "station_id": "a", "fetched_at": idx,
...     "num_bikes_available": [0, 5, 10, 5], "num_docks_available": [10, 5, 0, 5],
... })
>>> profiles, n_obs = diurnal_profiles(panel, min_obs=2)
>>> int(n_obs.loc[("s", "a")])
4
Source code in src/gbfs_toolkit/analytics/clustering.py
def diurnal_profiles(
    panel: pd.DataFrame,
    *,
    time_col: str = "fetched_at",
    split_weekday: bool = False,
    min_obs: int = 12,
) -> tuple[pd.DataFrame, pd.Series]:
    """Build each station's mean occupancy profile by hour of day.

    Robust to irregular sampling (aggregates by hour), fills an unobserved hour with the
    station's own mean. With ``split_weekday`` the profile is 48-dim (weekday ``wd*`` +
    weekend ``we*``), capturing commute-vs-leisure rhythms separately.

    Returns ``(profiles, n_obs)``; ``profiles`` indexed by ``(system_id, station_id)``
    with hour columns, and the per-station observation count.

    See Also
    --------
    [`cluster_diurnal_profiles`][gbfs_toolkit.cluster_diurnal_profiles] : Cluster these profiles into typologies.
    [`availability_stats`][gbfs_toolkit.availability_stats] : Scalar per-station statistics.

    Examples
    --------
    >>> import pandas as pd
    >>> idx = pd.date_range("2026-01-01", periods=4, freq="6h", tz="UTC")
    >>> panel = pd.DataFrame({
    ...     "system_id": "s", "station_id": "a", "fetched_at": idx,
    ...     "num_bikes_available": [0, 5, 10, 5], "num_docks_available": [10, 5, 0, 5],
    ... })
    >>> profiles, n_obs = diurnal_profiles(panel, min_obs=2)
    >>> int(n_obs.loc[("s", "a")])
    4
    """
    df = panel_frame(panel)
    df = df.copy()
    df["_occ"] = _capacity_fill(df)
    ts = pd.to_datetime(df[time_col], utc=True)
    df["_hour"] = ts.dt.hour
    n_obs = df.groupby(["system_id", "station_id"])["_occ"].count()

    if split_weekday:
        df["_seg"] = np.where(ts.dt.dayofweek < 5, "wd", "we")
        df["_col"] = df["_seg"] + df["_hour"].map(lambda h: f"{h:02d}")
        order = [f"{s}{h:02d}" for s in ("wd", "we") for h in range(24)]
    else:
        df["_col"] = df["_hour"].map(lambda h: f"h{h:02d}")
        order = [f"h{h:02d}" for h in range(24)]

    prof = df.pivot_table(index=["system_id", "station_id"], columns="_col", values="_occ")
    prof = prof.reindex(columns=order)
    prof = prof.apply(lambda row: row.fillna(row.mean()), axis=1).dropna(how="any")
    keep = n_obs[n_obs >= min_obs].index
    prof = prof.loc[prof.index.intersection(keep)]
    return prof, n_obs