Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 82 additions & 6 deletions docs/user_guide/timeseries/forecasting/LagFeatures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ executing `X[my_variable].shift(freq=”1H”, axis=0)`, we create a new feature
lagged values of `my_variable` by 1 hour.

Feature-engine’s :class:`LagFeatures` automates the creation of lag features from multiple
variables and by using multiple lags. It uses pandas `shift` under the hood, and automatically
concatenates the new features to the input dataframe.
variables and by using multiple lags. It works with pandas and polars dataframes, and
automatically adds the new features to the input dataframe.

Automating lag feature creation
-------------------------------
Expand All @@ -40,7 +40,8 @@ takes integers that indicate the number of rows forward that the features will b

Alternatively, we can use the parameter `freq`, which takes a string with the period and
frequency, and lags features based on the datetime index. For example, if we pass `freq="1D"`,
the values of the features will be moved 1 day forward.
the values of the features will be moved 1 day forward. `freq` needs a pandas dataframe
with a datetime index; with polars, use `periods`.

The :class:`LagFeatures` transformer works very similarly to `pandas.shift`, but unlike
`pandas.shift` we can indicate the lag using either `periods` or `freq` but not both at the
Expand All @@ -52,8 +53,13 @@ same time. Also, unlike `pandas.shift`, we can only lag features forward.
- Second, it adds the features with a name to the original dataframe.
- Third, it has the methods `fit()` and `transform()` that make it compatible with the scikit-learn's `Pipeline` and cross-validation functions.

Note that, in the current implementation, :class:`LagFeatures` only works with dataframes whose index,
containing the time series timestamp, contains unique values and no NaN.
With pandas dataframes, the index, containing the time series timestamp, gives the time
order of the rows. It must contain unique values and no NaN. By default, :class:`LagFeatures`
sorts the rows by the index before creating the lag features; set `sort_index=False` to
use the rows in the order given.

polars dataframes have no index, so :class:`LagFeatures` uses the rows in the order in which
they are in the dataframe. Sort the dataframe by time before creating the lag features.

.. attention::

Expand Down Expand Up @@ -528,7 +534,7 @@ This is the resulting output:
2020-05-15 13:15:00 32.50
2020-05-15 13:30:00 32.52
2020-05-15 13:45:00 32.68
Freq: 15T, Name: ambient_temp, dtype: float64
Freq: 15min, Name: ambient_temp, dtype: float64

We can use :class:`LagFeatures` to create, for example, 3 features by lagging the
pandas Series if we convert it to a pandas Dataframe using the method `to_frame()`:
Expand Down Expand Up @@ -588,6 +594,76 @@ The original variable is no longer in the output dataframe:
2020-05-15 12:45:00 31.31
2020-05-15 13:00:00 31.51

With polars
~~~~~~~~~~~

:class:`LagFeatures` works in the same way with a polars dataframe. polars dataframes have
no index, so the lag features are created with the rows in the order given. We sort the
dataframe by the date column first, to make sure the rows are in time order:

.. code:: python

from datetime import datetime

import polars as pl
from feature_engine.timeseries.forecasting import LagFeatures

X_pl = pl.DataFrame({
"date": pl.datetime_range(
datetime(2020, 5, 15, 12), datetime(2020, 5, 15, 13, 45), "15m", eager=True
),
"ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68],
"module_temp": [49.18, 49.84, 52.35, 50.63, 49.61, 47.01, 46.67, 47.52],
})
y_pl = pl.Series("y", [1, 2, 3, 4, 5, 6, 7, 8])

X_pl = X_pl.sort("date")

lag_f = LagFeatures(periods=1)

X_tr = lag_f.fit_transform(X_pl)

print(X_tr.head())

The numerical variables were lagged 1 row forward. The date column is not numerical, so
it was not lagged. In polars, the missing values are shown as null:

.. code:: text

shape: (5, 5)
┌─────────────────────┬──────────────┬─────────────┬────────────────────┬───────────────────┐
│ date ┆ ambient_temp ┆ module_temp ┆ ambient_temp_lag_1 ┆ module_temp_lag_1 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ datetime[μs] ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞═════════════════════╪══════════════╪═════════════╪════════════════════╪═══════════════════╡
│ 2020-05-15 12:00:00 ┆ 31.31 ┆ 49.18 ┆ null ┆ null │
│ 2020-05-15 12:15:00 ┆ 31.51 ┆ 49.84 ┆ 31.31 ┆ 49.18 │
│ 2020-05-15 12:30:00 ┆ 32.15 ┆ 52.35 ┆ 31.51 ┆ 49.84 │
│ 2020-05-15 12:45:00 ┆ 32.39 ┆ 50.63 ┆ 32.15 ┆ 52.35 │
│ 2020-05-15 13:00:00 ┆ 32.62 ┆ 49.61 ┆ 32.39 ┆ 50.63 │
└─────────────────────┴──────────────┴─────────────┴────────────────────┴───────────────────┘

We can also drop the rows with missing data in the lag features from the dataframe and
the target:

.. code:: python

lag_f = LagFeatures(periods=[1, 2], drop_na=True)

lag_f.fit(X_pl)

X_tr, y_tr = lag_f.transform_x_y(X_pl, y_pl)

X_tr.shape, y_tr.shape, X_pl.shape, y_pl.shape

The first 2 rows, which have no values 2 rows before, were removed from both:

.. code:: python

((6, 7), (6,), (8, 3), (8,))

The parameter `sort_index` has no effect with polars dataframes, and `freq` is only
supported with pandas dataframes.

Getting the name of the lag features
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
31 changes: 31 additions & 0 deletions feature_engine/dataframe_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,37 @@ def missing_values_mask(
return X.select(nw.col(var).is_null() for var in variables).to_numpy()


def rows_with_missing_values(
X: DataFrame, variables: Sequence[Union[str, int]]
) -> np.ndarray:
"""
Returns which rows have missing values in any of the variables.

Parameters
----------
X : pandas or narwhals dataframe
The dataframe returned by `check_X`.

variables : list
The names of the variables.

Returns
-------
mask : numpy array of shape = [n_samples]
True for the rows with at least one missing value.
"""
# pandas is faster than narwhals.
if not isinstance(X, nw.DataFrame):
return X[list(variables)].isna().to_numpy().any(axis=1)
elif len(variables) == 0:
return np.zeros(X.shape[0], dtype=bool)
else:
is_missing = nw.any_horizontal(
(nw.col(var).is_null() for var in variables), ignore_nulls=True
)
return X.select(is_missing).to_numpy()[:, 0]


def missing_values_count(
X: DataFrame, variables: Sequence[Union[str, int]]
) -> List[int]:
Expand Down
36 changes: 3 additions & 33 deletions feature_engine/imputation/drop_missing_data.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# Authors: Pradumna Suryawanshi <pradumnasuryawanshi@gmail.com>
# License: BSD 3 clause

from typing import List, Optional, Sequence, Union
from typing import List, Optional, Union

import narwhals as nw
import numpy as np
from narwhals.typing import IntoDataFrame, IntoSeries

from feature_engine._base_transformers.mixins import TransformXyMixin
Expand All @@ -25,45 +24,16 @@
from feature_engine._docstrings.substitute import Substitution
from feature_engine.dataframe_checks import check_X
from feature_engine.dataframe_helpers import (
DataFrame,
filter_rows,
missing_values_count,
missing_values_mask,
rows_with_missing_values,
)
from feature_engine.imputation.base_imputer import BaseImputer
from feature_engine.tags import _return_tags
from feature_engine.variable_handling import check_all_variables, find_all_variables


def _rows_with_missing_values(
X: DataFrame, variables: Sequence[Union[str, int]]
) -> np.ndarray:
"""
Returns which rows have missing values in any of the variables.

Parameters
----------
X : pandas or narwhals dataframe
The dataframe returned by `check_X`.

variables : list
The names of the variables.

Returns
-------
mask : numpy array of shape = [n_samples]
True for the rows with at least one missing value.
"""
# pandas is faster than narwhals.
if not isinstance(X, nw.DataFrame):
return X[list(variables)].isna().to_numpy().any(axis=1)
else:
is_missing = nw.any_horizontal(
(nw.col(var).is_null() for var in variables), ignore_nulls=True
)
return X.select(is_missing).to_numpy()[:, 0]


@Substitution(
return_empty=_return_empty_docstring,
feature_names_in_=_feature_names_in_docstring,
Expand Down Expand Up @@ -293,7 +263,7 @@ def _select_rows(self, X, keep: bool) -> IntoDataFrame:
non_null_count = (~is_missing).sum(axis=1)
mask = non_null_count >= len(self.variables_) * self.threshold
else:
mask = ~_rows_with_missing_values(X, self.variables_)
mask = ~rows_with_missing_values(X, self.variables_)
if keep is False:
mask = ~mask
return nw.to_native(filter_rows(X, mask), pass_through=True)
Expand Down
84 changes: 82 additions & 2 deletions feature_engine/timeseries/forecasting/_forecasting_helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Functions to check and sort the rows of a dataframe in time.
"""Functions to order the rows of a dataframe in time and add forecasting features.

With pandas, the rows are ordered in time by the dataframe's index. Other
dataframes, like polars, have no index: their rows are taken in the order given.
Expand All @@ -9,7 +9,7 @@
narwhals dataframe for the other libraries.
"""

from typing import Any, Union
from typing import Any, List, Optional, Sequence, Union

import narwhals as nw
from narwhals.typing import IntoDataFrame
Expand Down Expand Up @@ -75,3 +75,83 @@ def sort_by_index(X: DataFrame) -> DataFrame:
return X.sort_index()
else:
return X


def add_lag_features(
X: DataFrame,
variables: Sequence[Union[str, int]],
periods: List[int],
freq: Optional[List[Any]],
fill_value: Any,
names: List[str],
) -> DataFrame:
"""
Adds the lags of the variables after the columns of the dataframe.

Parameters
----------
X : pandas or narwhals dataframe
The dataframe returned by `check_X`.

variables : list
The names of the variables to lag.

periods : list
The number of rows to shift. Used when `freq` is None.

freq : list or None
The time spans to shift the pandas index by: strings, like "1h", or pandas
offsets.

fill_value :
The value for the rows that have no past values. If None, they are missing.

names : list
The names of the lags: for each period or freq, one per variable.

Returns
-------
X : pandas or narwhals dataframe
The dataframe with the lags.
"""
# pandas is faster than narwhals, and freq needs the pandas index.
if not isinstance(X, nw.DataFrame):
if freq is None:
lags = [X[list(variables)].shift(periods=periods, fill_value=fill_value)]
else:
lags = [X[list(variables)].shift(freq=fr) for fr in freq]
# joining one lag at a time is faster than aligning all lags at once.
new_names = iter(names)
for lag in lags:
lag.columns = [next(new_names) for _ in lag.columns]
X = X.join(lag)
# shift() does not take fill_value together with freq.
if freq is not None and fill_value is not None:
X = X.fillna({name: fill_value for name in names})
else:
lags = list(zip([(var, pr) for pr in periods for var in variables], names))
if fill_value is None:
X = X.with_columns(
nw.col(var).shift(pr).alias(name) for (var, pr), name in lags
)
elif X.implementation is nw.Implementation.POLARS:
# polars is faster than narwhals: it fills the rows that shift()
# introduces without copying the column.
col = nw.get_native_namespace(X).col
X_pl = X.to_native().with_columns(
col(var).shift(pr, fill_value=fill_value).alias(name)
for (var, pr), name in lags
)
X = nw.from_native(X_pl, eager_only=True)
else:
# narwhals' shift() has no fill_value. The mask is True in the first
# rows, which have no past values, so missing data in X is not filled.
X = X.with_columns(
nw.when(nw.col(var).is_null().shift(pr).is_null())
.then(nw.lit(fill_value))
.otherwise(nw.col(var).shift(pr))
.alias(name)
for (var, pr), name in lags
)

return X
Loading