← Back to the chapter · Previous detail · Next detail →

Technical detail · Imputation and Noise Filtering

Interpolate only bounded gaps

def linear_interpolate(data, timestamps):
    """
    Interpolate missing values (None/NaN) using linear interpolation.
    Requires knowledge of surrounding valid points.
    """
    import numpy as np

    data = np.array(data, dtype=float)
    timestamps = np.array(timestamps, dtype=float)

    valid_mask = ~np.isnan(data)
    valid_indices = np.where(valid_mask)[0]

    if len(valid_indices) < 2:
        return data

    # Interpolate
    interpolated = np.interp(
        timestamps,
        timestamps[valid_mask],
        data[valid_mask],
        left=np.nan, right=np.nan
    )

    return interpolated

← Back to the chapter · Previous detail · Next detail →