diff --git a/docs/user_guide/timeseries/forecasting/LagFeatures.rst b/docs/user_guide/timeseries/forecasting/LagFeatures.rst index 2e9941b0c..23b73c4bb 100644 --- a/docs/user_guide/timeseries/forecasting/LagFeatures.rst +++ b/docs/user_guide/timeseries/forecasting/LagFeatures.rst @@ -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 ------------------------------- @@ -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 @@ -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:: @@ -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()`: @@ -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 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/feature_engine/dataframe_helpers.py b/feature_engine/dataframe_helpers.py index 8f38e1b13..9727096f8 100644 --- a/feature_engine/dataframe_helpers.py +++ b/feature_engine/dataframe_helpers.py @@ -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]: diff --git a/feature_engine/imputation/drop_missing_data.py b/feature_engine/imputation/drop_missing_data.py index f20fd8468..6e6293f05 100644 --- a/feature_engine/imputation/drop_missing_data.py +++ b/feature_engine/imputation/drop_missing_data.py @@ -1,10 +1,9 @@ # Authors: Pradumna Suryawanshi # 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 @@ -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, @@ -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) diff --git a/feature_engine/timeseries/forecasting/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index d38f734f2..006640a1b 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -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. @@ -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 @@ -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 diff --git a/feature_engine/timeseries/forecasting/lag_features.py b/feature_engine/timeseries/forecasting/lag_features.py index 578802d43..0ea15b70e 100644 --- a/feature_engine/timeseries/forecasting/lag_features.py +++ b/feature_engine/timeseries/forecasting/lag_features.py @@ -4,7 +4,8 @@ from collections.abc import Hashable from typing import List, Union -import pandas as pd +import narwhals as nw +from narwhals.typing import IntoDataFrame from feature_engine._docstrings.fit_attributes import ( _feature_names_in_docstring, @@ -21,6 +22,14 @@ _fit_transform_docstring, ) from feature_engine._docstrings.substitute import Substitution +from feature_engine.dataframe_helpers import ( + drop_variables_from_df, + filter_rows, + rows_with_missing_values, +) +from feature_engine.timeseries.forecasting._forecasting_helpers import ( + add_lag_features, +) from feature_engine.timeseries.forecasting.base_forecast_transformers import ( BaseForecastTransformer, ) @@ -41,13 +50,15 @@ class LagFeatures(BaseForecastTransformer): LagFeatures adds lag features to the dataframe. A lag feature is a feature with information about a prior time step. - LagFeatures has the same functionality as pandas `shift()` with the exception that - only one of `periods` or `freq` can be indicated at a time. LagFeatures builds on - top of pandas `shift()` in that multiple lags can be created at the same time and - the features with names will be concatenated to the original dataframe. + LagFeatures works like pandas `shift()`, with the exception that only one of + `periods` or `freq` can be indicated at a time. LagFeatures builds on top of + `shift()` in that multiple lags can be created at the same time, and the features + are added with names to the original dataframe. - To be compatible with LagFeatures, the dataframe's index must have unique values - and no NaN. + LagFeatures takes pandas and polars dataframes, among others. With pandas, the + index gives the time order of the rows, so it must have unique values and no NaN. + polars dataframes have no index: LagFeatures uses the rows in the order given, so + sort them by time first. LagFeatures works only with numerical variables. You can pass a list of variables to lag. Alternatively, LagFeatures will automatically select and lag all numerical @@ -70,16 +81,19 @@ class LagFeatures(BaseForecastTransformer): Offset to use from the tseries module or time rule. See parameter `freq` in pandas `shift()`. It is the same functionality. If freq is a list, lag features will be created for each one of the frequency values in the list. If freq is not - None, then this parameter overrides the parameter `periods`. + None, then this parameter overrides the parameter `periods`. `freq` lags the + values based on the dataframe's DatetimeIndex, so it is only supported with + pandas dataframes. With polars, use `periods` instead. fill_value: object, optional - The scalar value to use for newly introduced missing values. The default - depends on the dtype of the variable. For numeric data, np.nan is used. For - datetime, timedelta, or period data, NaT is used. For extension dtypes, - self.dtype.na_value is used. + The scalar value to use for the missing values introduced by the lags. If None, + the lag features show missing values (NaN in pandas, null in polars) in the + rows that have no past values. sort_index: bool, default=True Whether to order the index of the dataframe before creating the lag features. + Only applies to pandas dataframes. polars dataframes have no index, so their + rows are used in the order given. {missing_values} @@ -111,7 +125,8 @@ class LagFeatures(BaseForecastTransformer): See Also -------- - pandas.shift + pandas.DataFrame.shift + polars.Expr.shift Examples -------- @@ -134,6 +149,33 @@ class LagFeatures(BaseForecastTransformer): 2 2022-09-20 3 8 2.0 7.0 1.0 6.0 3 2022-09-21 4 9 3.0 8.0 2.0 7.0 4 2022-09-22 5 10 4.0 9.0 3.0 8.0 + + With polars: + + >>> import polars as pl + >>> from feature_engine.timeseries.forecasting import LagFeatures + >>> X = pl.DataFrame(dict(date = ["2022-09-18", + >>> "2022-09-19", + >>> "2022-09-20", + >>> "2022-09-21", + >>> "2022-09-22"], + >>> x1 = [1,2,3,4,5], + >>> x2 = [6,7,8,9,10] + >>> )) + >>> lf = LagFeatures(periods=[1,2]) + >>> lf.fit_transform(X) + shape: (5, 7) + ┌────────────┬─────┬─────┬──────────┬──────────┬──────────┬──────────┐ + │ date ┆ x1 ┆ x2 ┆ x1_lag_1 ┆ x2_lag_1 ┆ x1_lag_2 ┆ x2_lag_2 │ + │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ + │ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │ + ╞════════════╪═════╪═════╪══════════╪══════════╪══════════╪══════════╡ + │ 2022-09-18 ┆ 1 ┆ 6 ┆ null ┆ null ┆ null ┆ null │ + │ 2022-09-19 ┆ 2 ┆ 7 ┆ 1 ┆ 6 ┆ null ┆ null │ + │ 2022-09-20 ┆ 3 ┆ 8 ┆ 2 ┆ 7 ┆ 1 ┆ 6 │ + │ 2022-09-21 ┆ 4 ┆ 9 ┆ 3 ┆ 8 ┆ 2 ┆ 7 │ + │ 2022-09-22 ┆ 5 ┆ 10 ┆ 4 ┆ 9 ┆ 3 ┆ 8 │ + └────────────┴─────┴─────┴──────────┴──────────┴──────────┴──────────┘ """ def __init__( @@ -149,26 +191,34 @@ def __init__( drop_na: bool = False, ) -> None: - if not ( - isinstance(periods, int) - and periods > 0 - or isinstance(periods, list) - and all(isinstance(num, int) and num > 0 for num in periods) + periods_list = periods if isinstance(periods, list) else [periods] + # bool is a subclass of int, but True is not a number of periods. + if len(periods_list) == 0 or not all( + isinstance(pr, int) and not isinstance(pr, bool) and pr > 0 + for pr in periods_list ): - raise ValueError( - "periods must be an integer or a list of positive integers. " - f"Got {periods} instead." + "periods must be a positive integer or a non-empty list of positive " + f"integers. Got {periods} instead." + ) + if len(periods_list) != len(set(periods_list)): + raise ValueError( + f"There are duplicated periods in the list. Got {periods} instead." ) - if isinstance(periods, list) and len(periods) != len(set(periods)): - raise ValueError(f"There are duplicated periods in the list: {periods}") + if isinstance(freq, list) and len(freq) == 0: + raise ValueError( + "freq must be None, a frequency or a non-empty list of frequencies. " + f"Got {freq} instead." + ) if isinstance(freq, list) and len(freq) != len(set(freq)): - raise ValueError(f"There are duplicated freq values in the list: {freq}") + raise ValueError( + f"There are duplicated freq values in the list. Got {freq} instead." + ) if not isinstance(sort_index, bool): raise ValueError( - "sort_index takes values True and False." f"Got {sort_index} instead." + f"sort_index takes values True and False. Got {sort_index} instead." ) super().__init__( @@ -180,77 +230,40 @@ def __init__( self.fill_value = fill_value self.sort_index = sort_index - def transform(self, X: pd.DataFrame) -> pd.DataFrame: + def transform(self, X: IntoDataFrame) -> IntoDataFrame: """ Adds lag features. Parameters ---------- - X: pandas dataframe of shape = [n_samples, n_features] + X: dataframe of shape = [n_samples, n_features] The data to transform. Returns ------- - X_new: pandas dataframe, shape = [n_samples, n_features + lag_features] - The dataframe with the original plus the new variables. + X_new: dataframe of shape = [n_samples, n_features + lag_features] + The dataframe with the original plus the new variables. If + `drop_na=True`, rows with missing data in the lag features are removed. """ - # Common dataframe checks and setting up. X = self._check_transform_input_and_state(X) - # if freq is not None, it overrides periods. - if self.freq is not None: - - if isinstance(self.freq, list): - df_ls = [] - for fr in self.freq: - tmp = X[self.variables_].shift( - freq=fr, - axis=0, - ) - df_ls.append(tmp) - tmp = pd.concat(df_ls, axis=1, sort=False) - - else: - tmp = X[self.variables_].shift( - freq=self.freq, - axis=0, - ) - + periods = self.periods if isinstance(self.periods, list) else [self.periods] + if self.freq is None or isinstance(self.freq, list): + freq = self.freq else: - if isinstance(self.periods, list): - df_ls = [] - for pr in self.periods: - tmp = X[self.variables_].shift( - periods=pr, - fill_value=self.fill_value, - axis=0, - ) - df_ls.append(tmp) - tmp = pd.concat(df_ls, axis=1, sort=False) - - else: - tmp = X[self.variables_].shift( - periods=self.periods, - fill_value=self.fill_value, - axis=0, - ) - - tmp.columns = self._get_new_features_name() - - X = X.merge(tmp, left_index=True, right_index=True, how="left") - - # we need this because pandas deprecated fill_value when using frequency - if self.freq is not None and self.fill_value is not None: - lags = [x for x in tmp.columns if x not in self.feature_names_in_] - X[lags] = X[lags].fillna(value=self.fill_value) - - if self.drop_original: - X = X.drop(self.variables_, axis=1) - - if self.drop_na: - X = X.dropna(subset=tmp.columns, axis=0) - - return X + freq = [self.freq] + new_features = self._get_new_features_name() + X = add_lag_features( + X, self.variables_, periods, freq, self.fill_value, new_features + ) + + if self.drop_original is True: + X = drop_variables_from_df(X, self.variables_) + + if self.drop_na is True: + X = filter_rows(X, ~rows_with_missing_values(X, new_features)) + + return nw.to_native(X, pass_through=True) def _get_new_features_name(self) -> List: """Get names of the lag features.""" diff --git a/tests/test_dataframe_helpers.py b/tests/test_dataframe_helpers.py index b122e474d..6e4064669 100644 --- a/tests/test_dataframe_helpers.py +++ b/tests/test_dataframe_helpers.py @@ -19,6 +19,7 @@ missing_values_count, missing_values_mask, replace_columns_in_df, + rows_with_missing_values, subset_df, to_numpy, ) @@ -372,6 +373,29 @@ def test_missing_values_mask_with_empty_variables(make_df): assert missing_values_mask(X, []).shape == (4, 0) +# ------------------------ +# rows_with_missing_values +# ------------------------ + + +def test_rows_with_missing_values(make_df): + X = check_X(make_df({**DATA_NA, "var_d": [None, 1.0, 2.0, 3.0]})) + + assert rows_with_missing_values(X, ["var_a", "var_d"]).tolist() == [ + True, + True, + False, + False, + ] + assert rows_with_missing_values(X, ["var_c"]).tolist() == [False] * 4 + + +def test_rows_with_missing_values_with_empty_variables(make_df): + X = check_X(make_df(DATA_NA)) + + assert rows_with_missing_values(X, []).tolist() == [False] * 4 + + # ------------------------ # missing_values_count # ------------------------ diff --git a/tests/test_time_series/test_forecasting/test_forecasting_helpers.py b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py index 418882a04..c274554ce 100644 --- a/tests/test_time_series/test_forecasting/test_forecasting_helpers.py +++ b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py @@ -1,11 +1,13 @@ import re +import narwhals as nw import pandas as pd import polars as pl import pytest from feature_engine.dataframe_checks import check_X from feature_engine.timeseries.forecasting._forecasting_helpers import ( + add_lag_features, check_index, sort_by_index, ) @@ -67,3 +69,37 @@ def test_sort_by_index_sorts_pandas_rows_by_the_index(): def test_sort_by_index_keeps_the_row_order_with_polars(): X = check_X(pl.DataFrame({"a": [3, 1, 2]})) assert frame_to_dict(sort_by_index(X).to_native()) == {"a": [3, 1, 2]} + + +def test_add_lag_features(make_df): + X = check_X(make_df({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]})) + Xt = add_lag_features(X, ["a", "b"], [1, 2], None, None, ["a1", "b1", "a2", "b2"]) + + assert frame_to_dict(nw.to_native(Xt, pass_through=True)) == { + "a": [1.0, 2.0, 3.0], + "b": [4.0, 5.0, 6.0], + "a1": [None, 1.0, 2.0], + "b1": [None, 4.0, 5.0], + "a2": [None, None, 1.0], + "b2": [None, None, 4.0], + } + + +@pytest.mark.parametrize("backend", ["pandas", "polars", "narwhals"]) +def test_add_lag_features_with_fill_value(backend): + # a pandas dataframe in narwhals takes the path of the libraries other than + # pandas and polars + data = {"a": [1.0, None, 3.0]} + X = { + "pandas": check_X(pd.DataFrame(data)), + "polars": check_X(pl.DataFrame(data)), + "narwhals": nw.from_native(pd.DataFrame(data), eager_only=True), + }[backend] + Xt = add_lag_features(X, ["a"], [1], None, 0, ["a_lag"]) + + # the missing value of a is lagged, not filled + assert frame_to_dict(nw.to_native(Xt, pass_through=True))["a_lag"] == [ + 0, + 1.0, + None, + ] diff --git a/tests/test_time_series/test_forecasting/test_lag_features.py b/tests/test_time_series/test_forecasting/test_lag_features.py index 6694fcb69..eefaf1dfe 100644 --- a/tests/test_time_series/test_forecasting/test_lag_features.py +++ b/tests/test_time_series/test_forecasting/test_lag_features.py @@ -1,346 +1,201 @@ +import re + import numpy as np import pandas as pd import pytest from feature_engine.timeseries.forecasting import LagFeatures +from tests.backend_helpers import frame_to_dict, make_series +DATA = { + "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62], + "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61], + "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42], + "color": ["blue"] * 5, +} -@pytest.mark.parametrize("_periods", [1, [1, 2, 3]]) -def test_permitted_param_periods(_periods): - transformer = LagFeatures(periods=_periods) - assert transformer.periods == _periods +DATES = pd.date_range("2020-05-15 12:00:00", periods=5, freq="15min") +# init parameters +# the errors of the parameters from BaseForecastTransformer are tested in +# test_base_forecast_transformer.py @pytest.mark.parametrize( - "_periods", [-1, 0, None, [-1, 2, 3], [0.1, 1], 0.5, [0, 1], [1, 1, 2]] + "periods", + [-1, 0, None, True, [-1, 2, 3], [0.1, 1], 0.5, [0, 1], [True], [], "1", (1, 2)], ) -def test_error_when_non_permitted_param_periods(_periods): - with pytest.raises(ValueError): - LagFeatures(periods=_periods) - - -def test_error_when_non_permitted_param_freq(): - with pytest.raises(ValueError): - LagFeatures(freq=["2h", "2h", "3h"]) - - -@pytest.mark.parametrize("_drop_or", [-1, [0], None, 7, "hola"]) -def test_error_when_non_permitted_param_drop_original(_drop_or): - with pytest.raises(ValueError): - LagFeatures(drop_original=_drop_or) - - -@pytest.mark.parametrize("_drop_na", [-1, [0], None, 7, "hola"]) -def test_error_when_non_permitted_param_drop_na(_drop_na): - with pytest.raises(ValueError): - LagFeatures(drop_na=_drop_na) - - -@pytest.mark.parametrize("_sort_index", [True, False]) -def test_permitted_param_sort_index(_sort_index): - transformer = LagFeatures(sort_index=_sort_index) - assert transformer.sort_index == _sort_index - - -@pytest.mark.parametrize("_sort_index", [-1, None, "hola"]) -def test_error_when_non_permitted_param_sort_index(_sort_index): - with pytest.raises(ValueError): - LagFeatures(sort_index=_sort_index) - - -def test_get_feature_names_out(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] +def test_error_if_periods_not_permitted(periods): + msg = ( + "periods must be a positive integer or a non-empty list of positive " + f"integers. Got {periods} instead." + ) + with pytest.raises(ValueError, match=re.escape(msg)): + LagFeatures(periods=periods) - # When freq is a string: - tr = LagFeatures(freq="1D") - tr.fit(df_time) - # Expected - out = ["ambient_temp_lag_1D", "module_temp_lag_1D", "irradiation_lag_1D"] - out = original_features + out - assert tr.get_feature_names_out(input_features=None) == out - assert tr.get_feature_names_out(input_features=original_features) == out - assert tr.get_feature_names_out(input_features=df_time.columns) == out +def test_error_if_periods_duplicated(): + msg = "There are duplicated periods in the list. Got [1, 1, 2] instead." + with pytest.raises(ValueError, match=re.escape(msg)): + LagFeatures(periods=[1, 1, 2]) - with pytest.raises(ValueError): - # assert error when user passes a string instead of list - tr.get_feature_names_out(input_features=original_features[0]) - with pytest.raises(ValueError): - # assert error when uses passes features that were not lagged - tr.get_feature_names_out(input_features=["color"]) +def test_error_if_freq_empty_list(): + msg = ( + "freq must be None, a frequency or a non-empty list of frequencies. " + "Got [] instead." + ) + with pytest.raises(ValueError, match=re.escape(msg)): + LagFeatures(freq=[]) - # When period is an int: - tr = LagFeatures(periods=2) - tr.fit(df_time) - # Expected - out = ["ambient_temp_lag_2", "module_temp_lag_2", "irradiation_lag_2"] - out = original_features + out - assert tr.get_feature_names_out(input_features=None) == out - assert tr.get_feature_names_out(input_features=original_features) == out - assert tr.get_feature_names_out(input_features=df_time.columns) == out +def test_error_if_freq_duplicated(): + msg = ( + "There are duplicated freq values in the list. " + "Got ['2h', '2h', '3h'] instead." + ) + with pytest.raises(ValueError, match=re.escape(msg)): + LagFeatures(freq=["2h", "2h", "3h"]) - # When freq is a list: - tr = LagFeatures(freq=["3D", "2D"]) - tr.fit(df_time) - # Expected - out = [ - "ambient_temp_lag_3D", - "module_temp_lag_3D", - "irradiation_lag_3D", - "ambient_temp_lag_2D", - "module_temp_lag_2D", - "irradiation_lag_2D", - ] - out = original_features + out - - assert tr.get_feature_names_out(input_features=None) == out - assert tr.get_feature_names_out(input_features=df_time.columns) == out - - # When periods is a list: - tr = LagFeatures(periods=[2, 3]) - tr.fit(df_time) - - # Expected - out = [ - "ambient_temp_lag_2", - "module_temp_lag_2", - "irradiation_lag_2", - "ambient_temp_lag_3", - "module_temp_lag_3", - "irradiation_lag_3", - ] - out = original_features + out +@pytest.mark.parametrize("sort_index", [-1, 1, None, "hola", [True]]) +def test_error_if_sort_index_not_bool(sort_index): + msg = f"sort_index takes values True and False. Got {sort_index} instead." + with pytest.raises(ValueError, match=re.escape(msg)): + LagFeatures(sort_index=sort_index) - assert tr.get_feature_names_out(input_features=None) == out - assert tr.get_feature_names_out(input_features=original_features) == out - # When drop original is true. - tr = LagFeatures(freq="1D", drop_original=True) - tr.fit(df_time) +@pytest.mark.parametrize( + "periods, freq, fill_value, sort_index, missing_values, drop_original, drop_na", + [ + (1, None, None, True, "raise", False, False), + ([1, 2, 3], None, 0, False, "ignore", True, True), + (1, ["1h", "2h"], -1.5, True, "raise", False, True), + ], +) +def test_init_param_assignment( + periods, freq, fill_value, sort_index, missing_values, drop_original, drop_na +): + transformer = LagFeatures( + periods=periods, + freq=freq, + fill_value=fill_value, + sort_index=sort_index, + missing_values=missing_values, + drop_original=drop_original, + drop_na=drop_na, + ) + assert transformer.periods == periods + assert transformer.freq == freq + assert transformer.fill_value == fill_value + assert transformer.sort_index == sort_index + assert transformer.missing_values == missing_values + assert transformer.drop_original == drop_original + assert transformer.drop_na == drop_na + + +# fit and transform +def test_lags_all_numerical_variables_by_default(make_df): + X = make_df(DATA) + Xt = LagFeatures().fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "ambient_temp_lag_1": [None, 31.31, 31.51, 32.15, 32.39], + "module_temp_lag_1": [None, 49.18, 49.84, 52.35, 50.63], + "irradiation_lag_1": [None, 0.51, 0.79, 0.65, 0.76], + } - # Expected - out = ["ambient_temp_lag_1D", "module_temp_lag_1D", "irradiation_lag_1D"] - assert tr.get_feature_names_out(input_features=None) == ["color"] + out - assert tr.get_feature_names_out(input_features=original_features) == ["color"] + out +def test_lag_with_one_period(make_df): + X = make_df(DATA) + transformer = LagFeatures(variables=["ambient_temp", "module_temp"], periods=3) + Xt = transformer.fit_transform(X) -def test_correct_lag_when_using_periods(df_time): - # Expected - date_time = [ - pd.Timestamp("2020-05-15 12:00:00"), - pd.Timestamp("2020-05-15 12:15:00"), - pd.Timestamp("2020-05-15 12:30:00"), - pd.Timestamp("2020-05-15 12:45:00"), - pd.Timestamp("2020-05-15 13:00:00"), - ] - expected_results = { - "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62], - "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61], - "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42], - "color": ["blue"] * 5, - "ambient_temp_lag_3": [np.nan, np.nan, np.nan, 31.31, 31.51], - "module_temp_lag_3": [np.nan, np.nan, np.nan, 49.18, 49.84], - "ambient_temp_lag_2": [np.nan, np.nan, 31.31, 31.51, 32.15], - "module_temp_lag_2": [np.nan, np.nan, 49.18, 49.84, 52.35], + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "ambient_temp_lag_3": [None, None, None, 31.31, 31.51], + "module_temp_lag_3": [None, None, None, 49.18, 49.84], } - expected_results_df = pd.DataFrame(data=expected_results, index=date_time) - # When period is an int. - transformer = LagFeatures(variables=["ambient_temp", "module_temp"], periods=3) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df.drop(["ambient_temp_lag_2", "module_temp_lag_2"], axis=1) - ) - # When period is list. +def test_lag_with_list_of_periods(make_df): + X = make_df(DATA) transformer = LagFeatures(variables=["ambient_temp", "module_temp"], periods=[3, 2]) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals(expected_results_df) - - # When drop original is True - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], periods=[3, 2], drop_original=True - ) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df.drop(["ambient_temp", "module_temp"], axis=1) - ) - - -def test_correct_lag_when_using_freq(df_time): - # Expected - date_time = [ - pd.Timestamp("2020-05-15 12:00:00"), - pd.Timestamp("2020-05-15 12:15:00"), - pd.Timestamp("2020-05-15 12:30:00"), - pd.Timestamp("2020-05-15 12:45:00"), - pd.Timestamp("2020-05-15 13:00:00"), - ] - expected_results = { - "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62], - "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61], - "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42], - "color": ["blue"] * 5, - "ambient_temp_lag_1h": [np.nan, np.nan, np.nan, np.nan, 31.31], - "module_temp_lag_1h": [np.nan, np.nan, np.nan, np.nan, 49.18], - "irradiation_lag_1h": [np.nan, np.nan, np.nan, np.nan, 0.51], - "ambient_temp_lag_15min": [np.nan, 31.31, 31.51, 32.15, 32.39], - "module_temp_lag_15min": [np.nan, 49.18, 49.84, 52.35, 50.63], - "irradiation_lag_15min": [np.nan, 0.51, 0.79, 0.65, 0.76], + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "ambient_temp_lag_3": [None, None, None, 31.31, 31.51], + "module_temp_lag_3": [None, None, None, 49.18, 49.84], + "ambient_temp_lag_2": [None, None, 31.31, 31.51, 32.15], + "module_temp_lag_2": [None, None, 49.18, 49.84, 52.35], } - expected_results_df = pd.DataFrame( - data=expected_results, - index=date_time, - ) - # When freq is a string - transformer = LagFeatures(freq="1h") - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df.drop( - [ - "ambient_temp_lag_15min", - "module_temp_lag_15min", - "irradiation_lag_15min", - ], - axis=1, - ) - ) - # When freq is a list - transformer = LagFeatures(freq=["1h", "15min"]) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals(expected_results_df) - - # When drop original is True - transformer = LagFeatures(freq=["1h"], drop_original=True) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df[ - ["color", "ambient_temp_lag_1h", "module_temp_lag_1h", "irradiation_lag_1h"] - ] +def test_drop_original(make_df): + X = make_df(DATA) + transformer = LagFeatures( + variables=["ambient_temp", "module_temp"], periods=[3, 2], drop_original=True ) + Xt = transformer.fit_transform(X) - -@pytest.mark.parametrize("fill_val", [-1, 0, 15]) -def test_fill_value(df_time, fill_val): - # Expected - date_time = [ - pd.Timestamp("2020-05-15 12:00:00"), - pd.Timestamp("2020-05-15 12:15:00"), - pd.Timestamp("2020-05-15 12:30:00"), - pd.Timestamp("2020-05-15 12:45:00"), - pd.Timestamp("2020-05-15 13:00:00"), - ] - expected_results = { - "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62], - "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61], + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42], "color": ["blue"] * 5, - "ambient_temp_lag_3": [fill_val, fill_val, fill_val, 31.31, 31.51], - "module_temp_lag_3": [fill_val, fill_val, fill_val, 49.18, 49.84], - "ambient_temp_lag_2": [fill_val, fill_val, 31.31, 31.51, 32.15], - "module_temp_lag_2": [fill_val, fill_val, 49.18, 49.84, 52.35], + "ambient_temp_lag_3": [None, None, None, 31.31, 31.51], + "module_temp_lag_3": [None, None, None, 49.18, 49.84], + "ambient_temp_lag_2": [None, None, 31.31, 31.51, 32.15], + "module_temp_lag_2": [None, None, 49.18, 49.84, 52.35], } - expected_results_df = pd.DataFrame(data=expected_results, index=date_time) - # When period is an int. - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], periods=3, fill_value=fill_val - ) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df.drop(["ambient_temp_lag_2", "module_temp_lag_2"], axis=1) - ) - # When period is list. +@pytest.mark.parametrize("fill_value", [-1, 0, 15.5]) +def test_fill_value(make_df, fill_value): + X = make_df(DATA) transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], periods=[3, 2], fill_value=fill_val + variables=["ambient_temp", "module_temp"], periods=[3, 2], fill_value=fill_value ) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals(expected_results_df) + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "ambient_temp_lag_3": [fill_value, fill_value, fill_value, 31.31, 31.51], + "module_temp_lag_3": [fill_value, fill_value, fill_value, 49.18, 49.84], + "ambient_temp_lag_2": [fill_value, fill_value, 31.31, 31.51, 32.15], + "module_temp_lag_2": [fill_value, fill_value, 49.18, 49.84, 52.35], + } - # When drop original is True - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], - periods=[3, 2], - drop_original=True, - fill_value=fill_val, - ) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df.drop(["ambient_temp", "module_temp"], axis=1) - ) +def test_fill_value_does_not_fill_missing_data_of_the_variables(make_df): + X = make_df({"a": [1.0, None, 3.0, 4.0], "b": [10, 20, 30, 40]}) + transformer = LagFeatures(periods=[1, 2], fill_value=0, missing_values="ignore") + Xt = transformer.fit_transform(X) -@pytest.mark.parametrize("fill_val", [-1, 0, 15]) -def test_fill_value_with_freq(df_time, fill_val): - # Expected - date_time = [ - pd.Timestamp("2020-05-15 12:00:00"), - pd.Timestamp("2020-05-15 12:15:00"), - pd.Timestamp("2020-05-15 12:30:00"), - pd.Timestamp("2020-05-15 12:45:00"), - pd.Timestamp("2020-05-15 13:00:00"), - ] - expected_results = { - "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62], - "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61], - "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42], - "color": ["blue"] * 5, - "ambient_temp_lag_45min": [fill_val, fill_val, fill_val, 31.31, 31.51], - "module_temp_lag_45min": [fill_val, fill_val, fill_val, 49.18, 49.84], - "ambient_temp_lag_30min": [fill_val, fill_val, 31.31, 31.51, 32.15], - "module_temp_lag_30min": [fill_val, fill_val, 49.18, 49.84, 52.35], + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "a": [1.0, None, 3.0, 4.0], + "b": [10, 20, 30, 40], + "a_lag_1": [0, 1.0, None, 3.0], + "b_lag_1": [0, 10, 20, 30], + "a_lag_2": [0, 0, 1.0, None], + "b_lag_2": [0, 0, 10, 20], } - expected_results_df = pd.DataFrame(data=expected_results, index=date_time) - # When period is an int. - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], freq="45min", fill_value=fill_val - ) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df.drop( - ["ambient_temp_lag_30min", "module_temp_lag_30min"], axis=1 - ) - ) - # When period is list. +def test_drop_na(make_df): + X = make_df(DATA) transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], - freq=["45min", "30min"], - fill_value=fill_val, - ) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals(expected_results_df) - - # When drop original is True - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], - freq=["45min", "30min"], - drop_original=True, - fill_value=fill_val, - ) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(5).equals( - expected_results_df.drop(["ambient_temp", "module_temp"], axis=1) + variables=["ambient_temp", "module_temp"], periods=[3, 2], drop_na=True ) + Xt = transformer.fit_transform(X) - -def test_drop_na(df_time): - df = df_time.head(5).copy() - - # Expected - date_time = [ - pd.Timestamp("2020-05-15 12:45:00"), - pd.Timestamp("2020-05-15 13:00:00"), - ] - expected_results = { + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { "ambient_temp": [32.39, 32.62], "module_temp": [50.63, 49.61], "irradiation": [0.76, 0.42], @@ -350,78 +205,203 @@ def test_drop_na(df_time): "ambient_temp_lag_2": [31.51, 32.15], "module_temp_lag_2": [49.84, 52.35], } - expected_df = pd.DataFrame(data=expected_results, index=date_time) - # When period is an int. - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], periods=3, drop_na=True - ) - df_tr = transformer.fit_transform(df) - assert df_tr.equals( - expected_df.drop(["ambient_temp_lag_2", "module_temp_lag_2"], axis=1) - ) - - # When period is list. - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], periods=[3, 2], drop_na=True - ) - df_tr = transformer.fit_transform(df) - assert df_tr.equals(expected_df) +def test_transform_x_y(make_df): + X = make_df(DATA) + y = make_series(make_df, [1, 2, 3, 4, 5], name="y") + transformer = LagFeatures(variables="ambient_temp", periods=2, drop_na=True) + transformer.fit(X) -def test_transform_x_y(df_time): - df = df_time.head(5).copy() - y = pd.Series(np.zeros(len(df)), index=df.index) + Xt, yt = transformer.transform_x_y(X, y) - # Expected - date_time = [ - pd.Timestamp("2020-05-15 12:45:00"), - pd.Timestamp("2020-05-15 13:00:00"), - ] - expected_results = { - "ambient_temp": [32.39, 32.62], - "module_temp": [50.63, 49.61], - "irradiation": [0.76, 0.42], - "color": ["blue"] * 2, - "ambient_temp_lag_3": [31.31, 31.51], - "module_temp_lag_3": [49.18, 49.84], - "ambient_temp_lag_2": [31.51, 32.15], - "module_temp_lag_2": [49.84, 52.35], + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "ambient_temp": [32.15, 32.39, 32.62], + "module_temp": [52.35, 50.63, 49.61], + "irradiation": [0.65, 0.76, 0.42], + "color": ["blue"] * 3, + "ambient_temp_lag_2": [31.31, 31.51, 32.15], } - expected_df = pd.DataFrame(data=expected_results, index=date_time) + assert list(yt) == [3, 4, 5] - # When period is an int. - transformer = LagFeatures( - variables=["ambient_temp", "module_temp"], periods=3, drop_na=True + +def test_return_empty_without_numerical_variables(make_df): + X = make_df({"color": DATA["color"]}) + transformer = LagFeatures(return_empty=True, periods=[1, 2]).fit(X) + Xt = transformer.transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == {"color": DATA["color"]} + assert transformer.get_feature_names_out() == ["color"] + + +@pytest.mark.parametrize( + "periods, drop_original, expected", + [ + ( + 2, + False, + [ + "ambient_temp", + "module_temp", + "irradiation", + "color", + "ambient_temp_lag_2", + "module_temp_lag_2", + "irradiation_lag_2", + ], + ), + ( + [2, 3], + True, + [ + "color", + "ambient_temp_lag_2", + "module_temp_lag_2", + "irradiation_lag_2", + "ambient_temp_lag_3", + "module_temp_lag_3", + "irradiation_lag_3", + ], + ), + ], +) +def test_get_feature_names_out(make_df, periods, drop_original, expected): + X = make_df(DATA) + transformer = LagFeatures(periods=periods, drop_original=drop_original).fit(X) + + assert transformer.get_feature_names_out() == expected + assert transformer.get_feature_names_out(input_features=list(DATA)) == expected + assert list(transformer.transform(X).columns) == expected + + +def test_get_feature_names_out_raises_error_if_input_features_wrong(make_df): + transformer = LagFeatures().fit(make_df(DATA)) + + msg = "input_features must be a list or an array. Got color instead." + with pytest.raises(ValueError, match=re.escape(msg)): + transformer.get_feature_names_out(input_features="color") + + msg = "input_features is not equal to feature_names_in_" + with pytest.raises(ValueError, match=re.escape(msg)): + transformer.get_feature_names_out(input_features=["color"]) + + +# pandas: freq lags the rows based on the DatetimeIndex +def test_lag_with_freq_with_pandas(df_time): + transformer = LagFeatures(freq=["1h", "15min"]) + Xt = transformer.fit_transform(df_time) + + expected = pd.DataFrame( + { + **DATA, + "ambient_temp_lag_1h": [np.nan, np.nan, np.nan, np.nan, 31.31], + "module_temp_lag_1h": [np.nan, np.nan, np.nan, np.nan, 49.18], + "irradiation_lag_1h": [np.nan, np.nan, np.nan, np.nan, 0.51], + "ambient_temp_lag_15min": [np.nan, 31.31, 31.51, 32.15, 32.39], + "module_temp_lag_15min": [np.nan, 49.18, 49.84, 52.35, 50.63], + "irradiation_lag_15min": [np.nan, 0.51, 0.79, 0.65, 0.76], + }, + index=DATES, ) - df_tr = transformer.fit_transform(df) - assert df_tr.equals( - expected_df.drop(["ambient_temp_lag_2", "module_temp_lag_2"], axis=1) + pd.testing.assert_frame_equal(Xt.head(5), expected, check_freq=False) + assert len(Xt) == len(df_time) + + +@pytest.mark.parametrize( + "freq", [pd.offsets.Minute(15), pd.Timedelta("15min"), [pd.offsets.Minute(15)]] +) +def test_lag_with_pandas_offsets_as_freq(df_time, freq): + Xt = LagFeatures(variables="ambient_temp", freq=freq).fit_transform(df_time) + expected = LagFeatures(variables="ambient_temp", freq="15min").fit_transform( + df_time ) - assert len(df_tr) != len(y) - Xt, yt = transformer.transform_x_y(df, y) - assert len(Xt) == len(yt) - assert len(y) != len(yt) - assert (Xt.index == yt.index).all() + np.testing.assert_array_equal(Xt.iloc[:, -1], expected.iloc[:, -1]) -def test_sort_index(df_time): - X = df_time.copy() +def test_lag_with_freq_on_irregular_index_with_pandas(): + # rows with no data one hour before get missing values + index = pd.to_datetime( + ["2020-05-15 12:00", "2020-05-15 13:00", "2020-05-15 13:30", "2020-05-15 15:00"] + ) + X = pd.DataFrame({"a": [1.0, 2.0, 3.0, 4.0]}, index=index) + Xt = LagFeatures(freq="1h", drop_original=True).fit_transform(X) - # Shuffle dataframe - Xs = X.sample(len(df_time)).copy() + expected = pd.DataFrame({"a_lag_1h": [np.nan, 1.0, np.nan, np.nan]}, index=index) + pd.testing.assert_frame_equal(Xt, expected) - transformer = LagFeatures(sort_index=True) - X_tr = transformer.fit_transform(Xs) - A = X[transformer.variables_].iloc[0:4].values - B = X_tr[transformer._get_new_features_name()].iloc[1:5].values - assert (A == B).all() +@pytest.mark.parametrize("fill_value", [-1, 0, 15]) +def test_fill_value_with_freq_with_pandas(df_time, fill_value): + transformer = LagFeatures( + variables=["ambient_temp", "module_temp"], + freq=["45min", "30min"], + fill_value=fill_value, + drop_original=True, + ) + Xt = transformer.fit_transform(df_time) + + expected = pd.DataFrame( + { + "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42], + "color": ["blue"] * 5, + "ambient_temp_lag_45min": [fill_value] * 3 + [31.31, 31.51], + "module_temp_lag_45min": [fill_value] * 3 + [49.18, 49.84], + "ambient_temp_lag_30min": [fill_value] * 2 + [31.31, 31.51, 32.15], + "module_temp_lag_30min": [fill_value] * 2 + [49.18, 49.84, 52.35], + }, + index=DATES, + ) + pd.testing.assert_frame_equal(Xt.head(5), expected, check_freq=False) + - transformer = LagFeatures(sort_index=False) - X_tr = transformer.fit_transform(Xs) +def test_get_feature_names_out_with_freq_with_pandas(df_time): + transformer = LagFeatures(freq=["3D", "2D"], drop_original=True).fit(df_time) - A = Xs[transformer.variables_].iloc[0:4].values - B = X_tr[transformer._get_new_features_name()].iloc[1:5].values - assert (A == B).all() + assert transformer.get_feature_names_out() == [ + "color", + "ambient_temp_lag_3D", + "module_temp_lag_3D", + "irradiation_lag_3D", + "ambient_temp_lag_2D", + "module_temp_lag_2D", + "irradiation_lag_2D", + ] + + +@pytest.mark.parametrize( + "sort_index, expected_index, expected_lag", + [ + (True, DATES, [np.nan, 31.31, 31.51, 32.15, 32.39]), + (False, DATES[[2, 0, 4, 1, 3]], [np.nan, 32.15, 31.31, 32.62, 31.51]), + ], +) +def test_sort_index_with_pandas(sort_index, expected_index, expected_lag): + X = pd.DataFrame(DATA, index=DATES).iloc[[2, 0, 4, 1, 3]] + transformer = LagFeatures(variables="ambient_temp", sort_index=sort_index) + Xt = transformer.fit_transform(X) + + expected = pd.DataFrame(DATA, index=DATES).loc[expected_index] + expected["ambient_temp_lag_1"] = expected_lag + pd.testing.assert_frame_equal(Xt, expected, check_freq=False) + + +def test_integer_column_names_with_pandas(): + X = pd.DataFrame({0: [1.0, 2.0, 3.0], 1: [4, 5, 6], "c": ["x", "y", "z"]}) + transformer = LagFeatures(periods=[1, 2], fill_value=0, drop_original=True) + Xt = transformer.fit(X).transform(X[["c", 1, 0]]) + + expected = pd.DataFrame( + { + "c": ["x", "y", "z"], + "0_lag_1": [0.0, 1.0, 2.0], + "1_lag_1": [0, 4, 5], + "0_lag_2": [0.0, 0.0, 1.0], + "1_lag_2": [0, 0, 4], + } + ) + # the columns started as a mix of integers and strings + expected.columns = expected.columns.astype(object) + pd.testing.assert_frame_equal(Xt, expected)