Skip to content

extract_snapshot_asof

extract_snapshot_asof

extract_snapshot_asof(panel: DataFrame, target_time: str | Timestamp, *, tolerance: str = '10min', time_col: str = 'fetched_at', by: tuple[str, ...] = ('system_id', 'station_id')) -> DataFrame

Extract the city's state at one instant: each station's last reading at or before T.

Stations answer at slightly different seconds, so "the state at 08:00" is not a clean slice. This returns, per station, the most recent observation in [target_time - tolerance, target_time], the cross-section a snapshot map or a point-in-time comparison needs, without a hand-rolled merge_asof.

Parameters:

Name Type Description Default
panel DataFrame

Panel/frame with the grouping columns in by and a time_col.

required
target_time str or Timestamp

The instant to reconstruct (naive is read as UTC).

required
tolerance str

How far before target_time a reading may be and still count.

"10min"
time_col see [`resample_panel`][gbfs_toolkit.resample_panel].
'fetched_at'
by see [`resample_panel`][gbfs_toolkit.resample_panel].
'fetched_at'

Returns:

Type Description
DataFrame

One row per group: its latest reading within the window (empty if none qualify).

See Also

resample_panel : Align the whole panel to a grid instead. to_wide_matrix : Pivot the panel to a station-by-time matrix.

Examples:

>>> import pandas as pd
>>> panel = pd.DataFrame({
...     "station_id": ["a", "a", "b"],
...     "fetched_at": pd.to_datetime(
...         ["2026-01-01T07:59Z", "2026-01-01T08:30Z", "2026-01-01T08:00Z"]),
...     "num_bikes_available": [3, 9, 7],
... })
>>> snap = extract_snapshot_asof(panel, "2026-01-01T08:00Z").set_index("station_id")
>>> int(snap.loc["a", "num_bikes_available"])
3
Source code in src/gbfs_toolkit/io/timeseries.py
def extract_snapshot_asof(
    panel: pd.DataFrame,
    target_time: str | pd.Timestamp,
    *,
    tolerance: str = "10min",
    time_col: str = "fetched_at",
    by: tuple[str, ...] = ("system_id", "station_id"),
) -> pd.DataFrame:
    """Extract the city's state at one instant: each station's last reading at or before ``T``.

    Stations answer at slightly different seconds, so "the state at 08:00" is not a clean
    slice. This returns, per station, the most recent observation in
    ``[target_time - tolerance, target_time]``, the cross-section a snapshot map or a
    point-in-time comparison needs, without a hand-rolled ``merge_asof``.

    Parameters
    ----------
    panel : pandas.DataFrame
        Panel/frame with the grouping columns in ``by`` and a ``time_col``.
    target_time : str or pandas.Timestamp
        The instant to reconstruct (naive is read as UTC).
    tolerance : str, default "10min"
        How far before ``target_time`` a reading may be and still count.
    time_col, by : see [`resample_panel`][gbfs_toolkit.resample_panel].

    Returns
    -------
    pandas.DataFrame
        One row per group: its latest reading within the window (empty if none qualify).

    See Also
    --------
    [`resample_panel`][gbfs_toolkit.resample_panel] : Align the whole panel to a grid instead.
    [`to_wide_matrix`][gbfs_toolkit.to_wide_matrix] : Pivot the panel to a station-by-time matrix.

    Examples
    --------
    >>> import pandas as pd
    >>> panel = pd.DataFrame({
    ...     "station_id": ["a", "a", "b"],
    ...     "fetched_at": pd.to_datetime(
    ...         ["2026-01-01T07:59Z", "2026-01-01T08:30Z", "2026-01-01T08:00Z"]),
    ...     "num_bikes_available": [3, 9, 7],
    ... })
    >>> snap = extract_snapshot_asof(panel, "2026-01-01T08:00Z").set_index("station_id")
    >>> int(snap.loc["a", "num_bikes_available"])
    3
    """
    df = panel_frame(panel).copy()
    keys = [k for k in by if k in df.columns]
    require_columns(df, [*keys, time_col], what="extract_snapshot_asof")
    df[time_col] = pd.to_datetime(df[time_col], utc=True)
    target = _as_utc(target_time)
    window = df[(df[time_col] <= target) & (df[time_col] >= target - pd.Timedelta(tolerance))]
    if window.empty:
        return df.iloc[:0].reset_index(drop=True)
    if not keys:
        return df.loc[[window[time_col].idxmax()]].reset_index(drop=True)
    idx = window.groupby(keys, sort=False)[time_col].idxmax()
    return df.loc[idx].reset_index(drop=True)