Skip to content

stockout_episodes

stockout_episodes

stockout_episodes(panel: DataFrame, *, kinds: tuple[str, ...] = ('empty', 'full')) -> DataFrame

Discrete empty/full episodes per station: the service-quality view of a panel.

Where coverage_report and availability_stats give fractions of time, this returns the individual outage events: each contiguous run of empty (no bikes) or full (no docks) snapshots becomes one row, so you can study how often stockouts happen and how long they last. Durations span the observed snapshots in the run (a single-observation episode has duration 0); read them together with coverage_report.

Parameters:

Name Type Description Default
panel DataFrame

From build_availability_panel (MultiIndexed) or a flat frame with system_id, station_id, fetched_at, num_bikes_available, num_docks_available.

required
kinds tuple of {"empty", "full"}

Which outage types to extract.

('empty', 'full')

Returns:

Type Description
DataFrame

One row per episode: system_id, station_id, kind, start, end, duration_minutes, n_obs (sorted by station then start).

See Also

detect_frozen_stations : Find stuck (never-changing) stations. build_availability_panel : The panel this scans.

Source code in src/gbfs_toolkit/io/timeseries.py
def stockout_episodes(
    panel: pd.DataFrame, *, kinds: tuple[str, ...] = ("empty", "full")
) -> pd.DataFrame:
    """Discrete empty/full episodes per station: the service-quality view of a panel.

    Where [`coverage_report`][gbfs_toolkit.coverage_report] and ``availability_stats`` give *fractions* of time, this
    returns the individual outage **events**: each contiguous run of empty (no bikes) or full
    (no docks) snapshots becomes one row, so you can study how *often* stockouts happen and how
    *long* they last. Durations span the observed snapshots in the run (a single-observation
    episode has duration 0); read them together with [`coverage_report`][gbfs_toolkit.coverage_report].

    Parameters
    ----------
    panel : pandas.DataFrame
        From [`build_availability_panel`][gbfs_toolkit.build_availability_panel] (MultiIndexed) or a flat frame with
        ``system_id, station_id, fetched_at, num_bikes_available, num_docks_available``.
    kinds : tuple of {"empty", "full"}
        Which outage types to extract.

    Returns
    -------
    pandas.DataFrame
        One row per episode: ``system_id, station_id, kind, start, end, duration_minutes,
        n_obs`` (sorted by station then start).

    See Also
    --------
    [`detect_frozen_stations`][gbfs_toolkit.detect_frozen_stations] : Find stuck (never-changing) stations.
    [`build_availability_panel`][gbfs_toolkit.build_availability_panel] : The panel this scans.
    """
    df = panel_frame(panel)
    require_columns(
        df,
        ["system_id", "station_id", "fetched_at", "num_bikes_available", "num_docks_available"],
        what="stockout_episodes",
    )
    df = df.sort_values(["system_id", "station_id", "fetched_at"])
    bikes = pd.to_numeric(df["num_bikes_available"], errors="coerce")
    docks = pd.to_numeric(df["num_docks_available"], errors="coerce")
    state = {"empty": bikes <= 0, "full": docks <= 0}

    rows = []
    keys = ["system_id", "station_id"]
    for kind in kinds:
        tmp = df[keys].copy()
        tmp["_flag"] = state[kind].to_numpy()
        # a new run starts whenever the flag changes (groupby shift resets at station bounds)
        shifted = tmp.groupby(keys, sort=False)["_flag"].shift()
        run = (tmp["_flag"] != shifted).cumsum()
        mask = tmp["_flag"].to_numpy()
        active = df[mask].assign(_run=run[mask].to_numpy())
        for (sid, stid, _r), g in active.groupby([*keys, "_run"], sort=False):
            start, end = g["fetched_at"].min(), g["fetched_at"].max()
            rows.append(
                {
                    "system_id": sid,
                    "station_id": stid,
                    "kind": kind,
                    "start": start,
                    "end": end,
                    "duration_minutes": round((end - start).total_seconds() / 60, 1),
                    "n_obs": int(len(g)),
                }
            )
    out = pd.DataFrame(rows, columns=_EPISODE_COLUMNS)
    return out.sort_values(["system_id", "station_id", "start"]).reset_index(drop=True)