Skip to content

temporal_autocorrelation

temporal_autocorrelation

temporal_autocorrelation(panel: DataFrame, *, lags: tuple[int, ...] = (1, 24, 168), freq: str = '1h', value_col: str = 'num_bikes_available', column: str | None = None) -> DataFrame

Per-station autocorrelation of availability at fixed lags (hour, day, week).

Each station's series is resampled to freq (mean) and correlated with itself at each lag. High autocorrelation at lag 24 (one day) marks a regular commuter rhythm; low autocorrelation everywhere marks an irregular or recreational station. A deterministic, descriptive precursor to (or substitute for) clustering.

Parameters:

Name Type Description Default
panel DataFrame

From build_availability_panel or a flat frame with system_id, station_id, fetched_at and value_col.

required
lags tuple of int

Lags in units of freq (with the default "1h": hour, day, week).

(1, 24, 168)
freq str

Resampling frequency.

"1h"
value_col str

Series to correlate.

"num_bikes_available"
column str

Deprecated alias for value_col (emits a FutureWarning).

None

Returns:

Type Description
DataFrame

system_id, station_id and one acf_lag_<k> column per lag (NaN when the resampled series is too short for that lag).

References

O'Brien, Cheshire and Batty (2014), Mining bike-sharing data for sustainable transport.

See Also

diurnal_summary_stats : The diurnal curve behind the rhythm. availability_synchrony : Cross-station correlation network.

Examples:

>>> import pandas as pd
>>> idx = pd.date_range("2026-01-01", periods=6, freq="1h", tz="UTC")
>>> panel = pd.DataFrame({
...     "system_id": "s", "station_id": "a", "fetched_at": idx,
...     "num_bikes_available": [0, 5, 0, 5, 0, 5],
... })
>>> round(float(temporal_autocorrelation(panel, lags=(2,))["acf_lag_2"].iloc[0]), 1)
1.0
Source code in src/gbfs_toolkit/analytics/temporal.py
def temporal_autocorrelation(
    panel: pd.DataFrame,
    *,
    lags: tuple[int, ...] = (1, 24, 168),
    freq: str = "1h",
    value_col: str = "num_bikes_available",
    column: str | None = None,
) -> pd.DataFrame:
    """Per-station autocorrelation of availability at fixed lags (hour, day, week).

    Each station's series is resampled to ``freq`` (mean) and correlated with itself at each
    lag. High autocorrelation at lag 24 (one day) marks a regular commuter rhythm; low
    autocorrelation everywhere marks an irregular or recreational station. A deterministic,
    descriptive precursor to (or substitute for) clustering.

    Parameters
    ----------
    panel : pandas.DataFrame
        From [`build_availability_panel`][gbfs_toolkit.build_availability_panel] or a flat frame with ``system_id, station_id,
        fetched_at`` and ``value_col``.
    lags : tuple of int, default (1, 24, 168)
        Lags in units of ``freq`` (with the default ``"1h"``: hour, day, week).
    freq : str, default "1h"
        Resampling frequency.
    value_col : str, default "num_bikes_available"
        Series to correlate.
    column : str, optional
        Deprecated alias for ``value_col`` (emits a ``FutureWarning``).

    Returns
    -------
    pandas.DataFrame
        ``system_id, station_id`` and one ``acf_lag_<k>`` column per lag (``NaN`` when the
        resampled series is too short for that lag).

    References
    ----------
    O'Brien, Cheshire and Batty (2014), Mining bike-sharing data for sustainable transport.

    See Also
    --------
    [`diurnal_summary_stats`][gbfs_toolkit.diurnal_summary_stats] : The diurnal curve behind the rhythm.
    [`availability_synchrony`][gbfs_toolkit.availability_synchrony] : Cross-station correlation network.

    Examples
    --------
    >>> import pandas as pd
    >>> idx = pd.date_range("2026-01-01", periods=6, freq="1h", tz="UTC")
    >>> panel = pd.DataFrame({
    ...     "system_id": "s", "station_id": "a", "fetched_at": idx,
    ...     "num_bikes_available": [0, 5, 0, 5, 0, 5],
    ... })
    >>> round(float(temporal_autocorrelation(panel, lags=(2,))["acf_lag_2"].iloc[0]), 1)
    1.0
    """
    if column is not None:
        value_col = deprecated_kwarg(column, old="column", new="value_col")
    df = panel_frame(panel)
    require_columns(
        df, ["system_id", "station_id", "fetched_at", value_col], what="temporal_autocorrelation"
    )
    df = df.sort_values(["system_id", "station_id", "fetched_at"])
    rows = []
    for (sid, stid), g in df.groupby(["system_id", "station_id"], sort=False):
        series = (
            pd.to_numeric(g.set_index("fetched_at")[value_col], errors="coerce")
            .resample(freq)
            .mean()
        )
        row: dict[str, Any] = {"system_id": sid, "station_id": stid}
        for lag in lags:
            row[f"acf_lag_{lag}"] = (
                series.autocorr(lag) if int(series.notna().sum()) > lag + 1 else np.nan
            )
        rows.append(row)
    return pd.DataFrame(rows)