Time series¶
Methods that use row order: carry-forward, interpolation, trends, seasonality and Kalman filtering.
Imputers that exploit row order, for time series and sequential data.
LOCFImputer
¶
Bases: BaseImputer
Impute using Last Observation Carried Forward (LOCF).
impute
¶
Fill missing values forward along each column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with potential NaN values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Dataframe where NaNs are replaced by the last seen observation. |
Source code in src/imputation_methods/time_series.py
NOCBImputer
¶
Bases: BaseImputer
Impute using Next Observation Carried Backward (NOCB).
impute
¶
ForwardFillFallbackImputer
¶
ForwardFillFallbackImputer(fallback: str = 'mean')
Bases: BaseImputer
Forward fill with fallback to mean/median for leading NaNs.
Combines LOCF with a fallback strategy for initial missing values that cannot be forward filled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fallback
|
str
|
Fallback strategy ('mean' or 'median'). Default: 'mean' |
'mean'
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import ForwardFillFallbackImputer
>>> df = pd.DataFrame({'a': [np.nan, np.nan, 3, np.nan, 5]})
>>> imputer = ForwardFillFallbackImputer(fallback='mean')
>>> imputed = imputer.impute(df)
>>> # First two NaNs filled with mean, third NaN forward filled
Initialize the forward fill fallback imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fallback
|
str
|
Fallback strategy ('mean' or 'median') |
'mean'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If fallback is not 'mean' or 'median' |
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using forward fill with fallback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
InterpolationImputer
¶
InterpolationImputer(method: str = 'linear', order: int = 2, limit: int | None = None, limit_direction: Literal['forward', 'backward', 'both'] = 'both')
Bases: BaseImputer
Impute missing values using interpolation methods.
Supports linear, polynomial, and spline interpolation for time series data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Interpolation method ('linear', 'polynomial', 'spline'). Default: 'linear' |
'linear'
|
order
|
int
|
Order for polynomial/spline interpolation. Default: 2 |
2
|
limit
|
int | None
|
Maximum number of consecutive NaNs to fill. Default: None (no limit) |
None
|
limit_direction
|
Literal['forward', 'backward', 'both']
|
Direction to fill ('forward', 'backward', 'both'). Default: 'both' |
'both'
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import InterpolationImputer
>>> df = pd.DataFrame({'a': [1, 2, np.nan, np.nan, 5]})
>>> imputer = InterpolationImputer(method='linear')
>>> imputed = imputer.impute(df)
>>> print(imputed['a'].tolist())
[1.0, 2.0, 3.0, 4.0, 5.0]
Initialize the interpolation imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Interpolation method |
'linear'
|
order
|
int
|
Polynomial/spline order |
2
|
limit
|
int | None
|
Maximum consecutive NaNs to fill |
None
|
limit_direction
|
Literal['forward', 'backward', 'both']
|
Fill direction |
'both'
|
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using interpolation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
MovingAverageImputer
¶
MovingAverageImputer(window: int = 3, strategy: str = 'mean', min_periods: int = 1, center: bool = False)
Bases: BaseImputer
Impute using moving average (rolling window).
Fills missing values with the mean or median of a rolling window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Size of the rolling window. Default: 3 |
3
|
strategy
|
str
|
Aggregation strategy ('mean' or 'median'). Default: 'mean' |
'mean'
|
min_periods
|
int
|
Minimum observations in window. Default: 1 |
1
|
center
|
bool
|
Whether to center the window. Default: False |
False
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import MovingAverageImputer
>>> df = pd.DataFrame({'a': [1, 2, np.nan, 4, np.nan, 6]})
>>> imputer = MovingAverageImputer(window=3, strategy='mean')
>>> imputed = imputer.impute(df)
Initialize the moving average imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Window size |
3
|
strategy
|
str
|
'mean' or 'median' |
'mean'
|
min_periods
|
int
|
Minimum observations required |
1
|
center
|
bool
|
Center the window |
False
|
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using moving average.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
WeightedMovingAverageImputer
¶
Bases: BaseImputer
Exponentially weighted moving average imputation for time series.
Uses exponential weighting to give more importance to recent values. More sophisticated than simple moving average for trending data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Smoothing factor (0 < alpha <= 1). Higher = more weight to recent. Default: 0.5 |
0.5
|
min_periods
|
int
|
Minimum observations needed. Default: 1 |
1
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import WeightedMovingAverageImputer
>>> df = pd.DataFrame({'a': [1, 2, np.nan, 4, np.nan, 6]})
>>> imputer = WeightedMovingAverageImputer(alpha=0.7)
>>> imputed = imputer.impute(df)
>>> # Missing values filled using exponentially weighted average
References
Commonly used in financial time series and sensor data analysis.
Initialize the weighted moving average imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Smoothing factor (0 < alpha <= 1) |
0.5
|
min_periods
|
int
|
Minimum observations required |
1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If alpha is not in (0, 1] |
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using exponentially weighted moving average.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
LinearTrendImputer
¶
LinearTrendImputer(use_index: bool = False)
Bases: BaseImputer
Linear trend imputation for time series data.
Fits a linear trend to observed data and uses it to fill missing values. Suitable for data with clear linear trends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_index
|
bool
|
Use dataframe index as x-values. If False, use integer positions. Default: False |
False
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import LinearTrendImputer
>>> df = pd.DataFrame({'a': [1, 2, np.nan, 4, np.nan, 6]})
>>> imputer = LinearTrendImputer()
>>> imputed = imputer.impute(df)
>>> # Missing values filled based on linear trend
References
Standard technique for trending time series data.
Initialize the linear trend imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_index
|
bool
|
Whether to use dataframe index as x-values |
False
|
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using linear trend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
PolynomialTrendImputer
¶
Bases: BaseImputer
Polynomial trend imputation for time series data.
Fits polynomial curve to observed data for non-linear trends. More flexible than linear trend for complex patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
degree
|
int
|
Polynomial degree (1=linear, 2=quadratic, 3=cubic, etc.). Default: 2 |
2
|
use_index
|
bool
|
Use dataframe index as x-values. Default: False |
False
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import PolynomialTrendImputer
>>> df = pd.DataFrame({'a': [1, 4, np.nan, 16, np.nan, 36]})
>>> imputer = PolynomialTrendImputer(degree=2)
>>> imputed = imputer.impute(df)
>>> # Missing values filled based on quadratic trend
References
Used for time series with non-linear but smooth trends.
Initialize the polynomial trend imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
degree
|
int
|
Polynomial degree (must be >= 1) |
2
|
use_index
|
bool
|
Whether to use dataframe index as x-values |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If degree < 1 |
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using polynomial trend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
SeasonalImputer
¶
Bases: BaseImputer
Impute using seasonal patterns.
Decomposes time series into seasonal components and uses seasonal averages for imputation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
int
|
Seasonal period (e.g., 24 for hourly data with daily seasonality, 7 for daily data with weekly seasonality). Default: 7 |
7
|
strategy
|
str
|
Aggregation strategy ('mean' or 'median'). Default: 'median' |
'median'
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import SeasonalImputer
>>> # Daily data with weekly seasonality
>>> df = pd.DataFrame({'sales': [100, 120, np.nan, 140, 130, np.nan, 90]})
>>> imputer = SeasonalImputer(period=7, strategy='median')
>>> imputed = imputer.impute(df)
Initialize the seasonal imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
int
|
Seasonal period |
7
|
strategy
|
str
|
'mean' or 'median' |
'median'
|
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using seasonal patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
KalmanFilterImputer
¶
KalmanFilterImputer(process_variance: float = 1.0, measurement_variance: float = 1.0, initial_state: float | None = None, initial_covariance: float = 1.0)
Bases: BaseImputer
Kalman filter imputation for time series with uncertainty.
Uses Kalman filtering to impute missing values while accounting for measurement noise and process uncertainty. Ideal for sensor data.
Algorithm Overview: The Kalman filter is a recursive Bayesian estimator that operates in two steps: 1. Prediction: Estimates the next state based on the previous state 2. Update: Corrects the prediction using new measurements
For imputation, when a measurement is missing, we use only the prediction step to fill the gap.
Mathematical Background: - State equation: x_k = x_{k-1} + w_k, where w_k ~ N(0, Q) - Measurement equation: z_k = x_k + v_k, where v_k ~ N(0, R) - Prediction: x_pred = x_est, P_pred = P_est + Q - Update: K = P_pred/(P_pred + R), x_est = x_pred + K*(z - x_pred)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_variance
|
float
|
Process noise variance (Q). Controls how much the state can vary between time steps. Larger values allow more flexibility but may lead to overfitting. Default: 1.0 |
1.0
|
measurement_variance
|
float
|
Measurement noise variance (R). Reflects confidence in observations. Larger values trust predictions more than measurements. Default: 1.0 |
1.0
|
initial_state
|
float | None
|
Initial state estimate. If None, uses first observed value. Default: None |
None
|
initial_covariance
|
float
|
Initial error covariance (P). Represents initial uncertainty in state estimate. Default: 1.0 |
1.0
|
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from imputation_methods import KalmanFilterImputer
>>> df = pd.DataFrame({'a': [1, np.nan, 3, np.nan, 5]})
>>> # High process variance allows more variation
>>> imputer = KalmanFilterImputer(process_variance=2.0)
>>> imputed = imputer.impute(df)
>>> # Missing values filled using Kalman filter estimates
References
Kalman, R. E. (1960). A new approach to linear filtering and prediction. Journal of Basic Engineering, 82(1), 35-45. Widely used in sensor fusion, GPS, and state estimation.
Notes
- Works best for time series data with smooth trends
- Assumes linear state transitions (constant velocity model)
- For non-linear systems, consider Extended Kalman Filter (EKF)
Initialize the Kalman filter imputer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_variance
|
float
|
Process noise variance (Q) |
1.0
|
measurement_variance
|
float
|
Measurement noise variance (R) |
1.0
|
initial_state
|
float | None
|
Initial state estimate (None = use first observed) |
None
|
initial_covariance
|
float
|
Initial error covariance (P) |
1.0
|
Source code in src/imputation_methods/time_series.py
impute
¶
Impute using Kalman filter.
The Kalman filter processes data sequentially, maintaining an estimate of the current state and its uncertainty. At each time step:
- Predict the next state using the state transition model
- If a measurement exists, update the estimate using Kalman gain
- If no measurement exists (NaN), use the prediction as the imputed value
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe with missing values. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Imputed dataframe. |
Source code in src/imputation_methods/time_series.py
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |