diff --git a/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst b/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst index 3d8714a67..2842b1769 100644 --- a/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst +++ b/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst @@ -32,7 +32,7 @@ For example, by executing: .. code:: python - X[["var_1", "var_2"].expanding(min_periods=3).agg(["max", "mean"]) + X[["var_1", "var_2"]].expanding(min_periods=3).agg(["max", "mean"]) With the previous command, we create 2 window features for each variable, `var_1` and `var_2`, by taking the maximum and average value of all observations up to (and including) @@ -43,7 +43,7 @@ we would also shift the window forward with pandas method `shift`: .. code:: python - X[["var_1", "var_2"].expanding(min_periods=3).agg(["max", "mean"]).shift(period=1) + X[["var_1", "var_2"]].expanding(min_periods=3).agg(["max", "mean"]).shift(periods=1) Expanding window features with feature-engine @@ -59,15 +59,23 @@ likely to be predictive. To capitalise on the past values of a variable, we can lag features with :class:`LagFeatures`. We can also create features that summarise the past values into a single quantity utilising :class:`ExpandingWindowFeatures`. -:class:`ExpandingWindowFeatures` works on top of `pandas.expanding`, `pandas.aggregate` -and `pandas.shift`. +:class:`ExpandingWindowFeatures` works with pandas and polars dataframes, and returns +the same type of dataframe it receives. -:class:`ExpandingWindowFeatures` uses `pandas.aggregate` to perform the mathematical -operations over the expanding window. Therefore, you can use any operation supported -by pandas. For supported aggregation functions, see Expanding Window +With pandas dataframes, :class:`ExpandingWindowFeatures` works on top of `pandas.expanding`, +`pandas.aggregate` and `pandas.shift`. It uses `pandas.aggregate` to perform the +mathematical operations over the expanding window. Therefore, you can use any method that +aggregates the values of one variable, like `"mean"`, `"max"` or `"std"`. For the +functions of your pandas version, see Expanding Window `Functions `_. -With `pandas.shift`, :class:`ExpandingWindowFeatures` lags the result of the expanding +With polars dataframes, :class:`ExpandingWindowFeatures` takes the functions `"count"`, +`"first"`, `"kurt"`, `"last"`, `"max"`, `"mean"`, `"median"`, `"min"`, `"nunique"`, +`"rank"`, `"sem"`, `"skew"`, `"std"`, `"sum"` and `"var"`. They compute the same +statistics as the pandas functions with the same name. `"rank"` needs polars 1.35 or +later. + +:class:`ExpandingWindowFeatures` lags the result of the expanding window operation. This is useful to ensure that only the information known at predict time is used to compute the window feature. So if at predict time we only know the value of a feature at the previous time period and before that, then we should lag the @@ -80,8 +88,10 @@ name to the original dataframe. It also 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:`ExpandingWindowFeatures` only works with -dataframes whose index, containing the time series timestamp, contains unique values and no NaN. +With pandas, :class:`ExpandingWindowFeatures` uses the dataframe's index, containing the +time series timestamp, to order the rows in time. The index must contain unique values +and no NaN. polars dataframes have no index, so the rows need to be in time order before +the transformation. See the section "With polars" below. .. attention:: @@ -366,7 +376,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:`ExpandingWindowFeatures` to create, for example, 2 new expanding window features by finding the mean and maximum value of a pandas Series if we convert @@ -450,6 +460,86 @@ We obtain the names of the original variables plus the new expanding window feat 'module_temp_expanding_mean', 'irradiation_expanding_mean'] +With polars +~~~~~~~~~~~ + +:class:`ExpandingWindowFeatures` also works with polars dataframes. polars dataframes have +no index, so the transformer takes the rows in the order in which they are in the +dataframe. Make sure the rows are sorted in time before creating the features. The +parameters `freq` and `sort_index` are only used with pandas. + +Let's create a polars dataframe whose rows are not in time order, and sort it by date: + +.. code:: python + + import polars as pl + from feature_engine.timeseries.forecasting import ExpandingWindowFeatures + + X = pl.DataFrame({ + "date": ["2020-05-15 12:30", "2020-05-15 12:00", "2020-05-15 13:00", + "2020-05-15 12:15", "2020-05-15 12:45"], + "ambient_temp": [32.15, 31.31, 32.62, 31.51, 32.39], + }) + + X = X.sort("date") + +Now we create the expanding mean and maximum of the temperature: + +.. code:: python + + win_f = ExpandingWindowFeatures(functions=["mean", "max"]) + + X_tr = win_f.fit_transform(X) + + print(X_tr) + +We obtain a polars dataframe with the new features. The first row has no past values, +so its expanding window features are null: + +.. code:: text + + shape: (5, 4) + ┌──────────────────┬──────────────┬─────────────────────────────┬────────────────────────────┐ + │ date ┆ ambient_temp ┆ ambient_temp_expanding_mean ┆ ambient_temp_expanding_max │ + │ --- ┆ --- ┆ --- ┆ --- │ + │ str ┆ f64 ┆ f64 ┆ f64 │ + ╞══════════════════╪══════════════╪═════════════════════════════╪════════════════════════════╡ + │ 2020-05-15 12:00 ┆ 31.31 ┆ null ┆ null │ + │ 2020-05-15 12:15 ┆ 31.51 ┆ 31.31 ┆ 31.31 │ + │ 2020-05-15 12:30 ┆ 32.15 ┆ 31.41 ┆ 31.51 │ + │ 2020-05-15 12:45 ┆ 32.39 ┆ 31.656667 ┆ 32.15 │ + │ 2020-05-15 13:00 ┆ 32.62 ┆ 31.84 ┆ 32.39 │ + └──────────────────┴──────────────┴─────────────────────────────┴────────────────────────────┘ + +Besides statistics like the mean, we can take the rank of the last past value among all +the past values, and the standard error of their mean: + +.. code:: python + + win_f = ExpandingWindowFeatures(functions=["rank", "sem"]) + + X_tr = win_f.fit_transform(X) + + print(X_tr) + +The temperature rises over time, so each past value is the highest so far, and its rank +is the number of past values: + +.. code:: text + + shape: (5, 4) + ┌──────────────────┬──────────────┬─────────────────────────────┬────────────────────────────┐ + │ date ┆ ambient_temp ┆ ambient_temp_expanding_rank ┆ ambient_temp_expanding_sem │ + │ --- ┆ --- ┆ --- ┆ --- │ + │ str ┆ f64 ┆ f64 ┆ f64 │ + ╞══════════════════╪══════════════╪═════════════════════════════╪════════════════════════════╡ + │ 2020-05-15 12:00 ┆ 31.31 ┆ null ┆ null │ + │ 2020-05-15 12:15 ┆ 31.51 ┆ 1.0 ┆ null │ + │ 2020-05-15 12:30 ┆ 32.15 ┆ 2.0 ┆ 0.1 │ + │ 2020-05-15 12:45 ┆ 32.39 ┆ 3.0 ┆ 0.253333 │ + │ 2020-05-15 13:00 ┆ 32.62 ┆ 4.0 ┆ 0.25632 │ + └──────────────────┴──────────────┴─────────────────────────────┴────────────────────────────┘ + See also -------- diff --git a/feature_engine/timeseries/forecasting/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index e3487ea77..c20fd5476 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -198,6 +198,31 @@ def add_lag_features( return X +def check_functions_supported( + X: DataFrame, functions: Union[str, List[str]] +) -> None: + """ + Checks that dataframes other than pandas use functions that they support. + + Parameters + ---------- + X : pandas or narwhals dataframe + The dataframe returned by `check_X`. + + functions : str or list + The `functions` parameter of the transformer. + """ + # pandas supports every function. + if isinstance(X, nw.DataFrame): + function_list = functions if isinstance(functions, list) else [functions] + supported = sorted([*_NW_ROLLING, *_POLARS_ROLLING, *_POLARS_ROW_WINDOWS]) + if not all(function in supported for function in function_list): + raise NotImplementedError( + "With dataframes other than pandas, functions takes only " + f"{supported}. Got {functions} instead." + ) + + def check_window_parameters( X: DataFrame, window: Any, @@ -232,13 +257,7 @@ def check_window_parameters( "other dataframes, window takes integers, the number of rows in " f"each window. Got {window} instead." ) - function_list = functions if isinstance(functions, list) else [functions] - supported = sorted([*_NW_ROLLING, *_POLARS_ROLLING, *_POLARS_ROW_WINDOWS]) - if not all(function in supported for function in function_list): - raise NotImplementedError( - "With dataframes other than pandas, functions takes only " - f"{supported}. Got {functions} instead." - ) + check_functions_supported(X, functions) if min_periods == 0: raise NotImplementedError( "min_periods=0 is only supported with pandas dataframes. With " @@ -341,3 +360,129 @@ def add_window_features( X = nw.from_native(X_pl, eager_only=True).select(columns + names) return X + + +def add_expanding_window_features( + X: DataFrame, + variables: Sequence[Union[str, int]], + functions: Union[str, List[str]], + min_periods: Optional[int], + periods: int, + freq: Optional[str], + ignore_missing: bool, + names: List[str], +) -> DataFrame: + """ + Adds functions of all the past values 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. + + functions : str or list + The functions to apply to the past values. + + min_periods : int or None + The minimum number of values to return a value. If None, 0. + + periods : int + The number of rows to shift the features by, so they hold past values only. + + freq : str or None + The time span to shift the pandas index by, instead of `periods`. + + ignore_missing : bool + Whether the variables can have missing values, NaN and inf. + + names : list + The names of the new features: for each variable, one per function. + + Returns + ------- + X : pandas or narwhals dataframe + The dataframe with the new features. + """ + # pandas is faster than narwhals, and freq shifts the pandas index. agg() is + # faster with one function as a string than as a list. + if not isinstance(X, nw.DataFrame): + tmp = ( + X[list(variables)] + .expanding(min_periods=min_periods) + .agg(functions) + .shift(periods=periods, freq=freq) + ) + tmp.columns = names + X = X.merge(tmp, left_index=True, right_index=True, how="left") + else: + # pandas treats min_periods=None as 0. narwhals' rolling functions need at + # least 1, and 0 only changes count and sum, done below. + min_periods = 0 if min_periods is None else min_periods + min_samples = max(min_periods, 1) + # a rolling window as long as the dataframe is an expanding window. + window = max(len(X), min_samples) + function_list = functions if isinstance(functions, list) else [functions] + new_features = [] + for var in variables: + # pandas computes in float and treats NaN as missing data, and inf too, + # except when counting. + x = nw.col(var).cast(nw.Float64) + if ignore_missing is True: + n_values = x.fill_nan(None).cum_count() + x = nw.when(x.is_finite()).then(x) + else: + n_values = x.cum_count() + count = x.cum_count() + # cumulative functions are faster than rolling ones, but they are null + # in the rows with missing data. + cumulative = { + "first": nw.when(~x.is_null() & (count == 1)).then(x), + "last": x, + "max": x.cum_max(), + "min": x.cum_min(), + } + for func in function_list: + if func == "count": + # pandas compares min_periods with the number of rows for count. + feature = nw.when(x.is_null().cum_count() >= min_periods).then( + n_values.cast(nw.Float64) + ) + elif func == "nunique": + # like the sum, it is 0 before the first value if min_periods=0. + feature = nw.when(count >= min_periods).then( + (x.is_first_distinct() & ~x.is_null()) + .cum_sum() + .cast(nw.Float64) + ) + elif func == "sem": + # pandas divides by the number of values, inf included. + feature = x.rolling_std( + window, min_samples=min_samples + ) / n_values.cast(nw.Float64).sqrt() + elif func in cumulative: + feature = nw.when(count >= min_samples).then( + cumulative[func].fill_null(strategy="forward") + ) + elif func in _NW_ROLLING: + feature = _NW_ROLLING[func](x, window, min_samples) + if func == "sum" and min_periods == 0: + feature = feature.fill_null(0) + else: + # narwhals has no rolling function for these: use polars' own + # on the series. + values = X.select(x).get_column(var).to_native() + feature = nw.from_native( + _POLARS_ROLLING[func](values, window, min_samples), + series_only=True, + ) + new_features.append(feature.shift(periods)) + + X = X.with_columns( + feature.alias(name) for feature, name in zip(new_features, names) + ) + + return X diff --git a/feature_engine/timeseries/forecasting/expanding_window_features.py b/feature_engine/timeseries/forecasting/expanding_window_features.py index c121734e1..46aa1bfc6 100644 --- a/feature_engine/timeseries/forecasting/expanding_window_features.py +++ b/feature_engine/timeseries/forecasting/expanding_window_features.py @@ -5,7 +5,8 @@ from typing import List -import pandas as pd +import narwhals as nw +from narwhals.typing import IntoDataFrame, IntoSeries from feature_engine._docstrings.fit_attributes import ( _feature_names_in_docstring, @@ -22,6 +23,16 @@ _fit_transform_docstring, ) from feature_engine._docstrings.substitute import Substitution +from feature_engine.dataframe_checks import check_X +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_expanding_window_features, + check_functions_supported, +) from feature_engine.timeseries.forecasting.base_forecast_transformers import ( BaseForecastTransformer, ) @@ -47,17 +58,21 @@ class ExpandingWindowFeatures(BaseForecastTransformer): window over all the past data. For example, the mean value of all months prior to the month of interest is an expanding window feature. - ExpandingWindowFeatures uses the pandas' functions `expanding()`, `agg()` and - `shift()`. With `expanding()`, it creates expanding windows. With `agg()` it - applies multiple functions within those windows. With 'shift()' it allocates - the values to the correct rows. + ExpandingWindowFeatures works with pandas and polars dataframes, and returns + the same type of dataframe it receives. - For supported aggregation functions, see Expanding Window + With pandas, ExpandingWindowFeatures uses the pandas' functions `expanding()`, + `agg()` and `shift()`. With `expanding()`, it creates expanding windows. With + `agg()` it applies multiple functions within those windows. With 'shift()' it + allocates the values to the correct rows. For supported aggregation functions, + see Expanding Window `Functions `_. + The dataframe's index orders the rows in time, so it must have unique values + and no NaN. - To be compatible with ExpandingWindowFeatures, the dataframe's index must - have unique values and no NaN. + polars dataframes have no index, so the rows must be sorted in time before using + the transformer, and `freq` and `sort_index` are not used. ExpandingWindowFeatures works only with numerical variables. You can pass a list of variables to use as input for the expanding window. Alternatively, @@ -74,24 +89,31 @@ class ExpandingWindowFeatures(BaseForecastTransformer): min_periods: int, default None. Minimum number of observations in window required to have a value; - otherwise, result is np.nan. See parameter `min_periods` in the pandas + otherwise, result is missing. See parameter `min_periods` in the pandas `expanding()` documentation for more details. functions: str, list of str, default = 'mean' - The functions to apply within the window. Valid functions can be found - `here `_. - - periods: int, list of ints, default=1 - Number of periods to shift. Can be a positive integer. See param `periods` in - pandas `shift`. - - freq: str, list of str, default=None + The functions to apply to the past values of each variable. With pandas, the + valid functions are the methods of pandas expanding windows that aggregate one + variable, like 'mean', 'max' or 'std'. See the pandas `documentation + `_ + for the functions of your pandas version. With polars, the valid functions are + 'count', 'first', 'kurt', 'last', 'max', 'mean', 'median', 'min', 'nunique', + 'rank', 'sem', 'skew', 'std', 'sum' and 'var', which compute the same + statistics as the pandas functions with the same name. 'rank' needs polars + 1.35 or later. + + periods: int, default=1 + Number of periods to shift. Can be zero or a positive integer. See param + `periods` in pandas `shift`. + + freq: str, default=None Offset to use from the tseries module or time rule. See parameter `freq` in - pandas `shift()`. + pandas `shift()`. Only supported with pandas dataframes. sort_index: bool, default=True Whether to order the index of the dataframe before creating the - expanding window feature. + expanding window feature. Only used with pandas dataframes. {missing_values} @@ -150,6 +172,33 @@ class ExpandingWindowFeatures(BaseForecastTransformer): 2 2022-09-20 3 8 1.5 6.5 3 2022-09-21 4 9 2.0 7.0 4 2022-09-22 5 10 2.5 7.5 + + With polars: + + >>> import polars as pl + >>> from feature_engine.timeseries.forecasting import ExpandingWindowFeatures + >>> 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] + >>> )) + >>> ewf = ExpandingWindowFeatures() + >>> ewf.fit_transform(X) + shape: (5, 5) + ┌────────────┬─────┬─────┬───────────────────┬───────────────────┐ + │ date ┆ x1 ┆ x2 ┆ x1_expanding_mean ┆ x2_expanding_mean │ + │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ + │ str ┆ i64 ┆ i64 ┆ f64 ┆ f64 │ + ╞════════════╪═════╪═════╪═══════════════════╪═══════════════════╡ + │ 2022-09-18 ┆ 1 ┆ 6 ┆ null ┆ null │ + │ 2022-09-19 ┆ 2 ┆ 7 ┆ 1.0 ┆ 6.0 │ + │ 2022-09-20 ┆ 3 ┆ 8 ┆ 1.5 ┆ 6.5 │ + │ 2022-09-21 ┆ 4 ┆ 9 ┆ 2.0 ┆ 7.0 │ + │ 2022-09-22 ┆ 5 ┆ 10 ┆ 2.5 ┆ 7.5 │ + └────────────┴─────┴─────┴───────────────────┴───────────────────┘ """ def __init__( @@ -166,21 +215,41 @@ def __init__( drop_na: bool = False, ) -> None: - if not isinstance(functions, (str, list)) or not all( - isinstance(val, str) for val in functions + if min_periods is not None and ( + not isinstance(min_periods, int) + or isinstance(min_periods, bool) + or min_periods < 0 + ): + raise ValueError( + "min_periods must be None or a non-negative integer. " + f"Got {min_periods} instead." + ) + + if ( + not isinstance(functions, (str, list)) + or len(functions) == 0 + or not all(isinstance(val, str) for val in functions) ): raise ValueError( - f"functions must be a list of strings or a string." + "functions must be a string or a non-empty list of strings. " f"Got {functions} instead." ) if isinstance(functions, list) and len(functions) != len(set(functions)): - raise ValueError(f"There are duplicated functions in the list: {functions}") + raise ValueError( + f"There are duplicated functions in the list. Got {functions} instead." + ) - if not isinstance(periods, int) or periods < 0: + # bool is a subclass of int, but True is not a number of periods. + if not isinstance(periods, int) or isinstance(periods, bool) or periods < 0: raise ValueError( f"periods must be a non-negative integer. Got {periods} instead." ) + if not isinstance(sort_index, bool): + raise ValueError( + f"sort_index takes values True and False. Got {sort_index} instead." + ) + super().__init__( variables, return_empty, missing_values, drop_original, drop_na ) @@ -191,54 +260,67 @@ def __init__( self.freq = freq self.sort_index = sort_index - def transform(self, X: pd.DataFrame) -> pd.DataFrame: + def fit(self, X: IntoDataFrame, y: IntoSeries | None = None): + """ + This transformer does not learn parameters. + + Parameters + ---------- + X: dataframe of shape = [n_samples, n_features] + The training dataset. + + y: Series, default=None + y is not needed in this transformer. You can pass None or y. + """ + super().fit(X, y) + check_functions_supported(check_X(X), self.functions) + return self + + def transform(self, X: IntoDataFrame) -> IntoDataFrame: """ Adds expanding window 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 + window_features] - The dataframe with the original plus the new variables. + X_new: dataframe of shape = [n_samples, n_features + window_features] + The dataframe with the original plus the new variables. If + `drop_na=True`, rows with missing data in the new features are removed. """ - # Common dataframe checks and setting up. X = self._check_transform_input_and_state(X) - tmp = ( - X[self.variables_] - .expanding(min_periods=self.min_periods) - .agg(self.functions) - .shift(periods=self.periods, freq=self.freq) - ) - - tmp.columns = self._get_new_features_name() - - X = X.merge(tmp, left_index=True, right_index=True, how="left") + new_features = self._get_new_features_name() + if len(self.variables_) > 0: + X = add_expanding_window_features( + X, + self.variables_, + self.functions, + self.min_periods, + self.periods, + self.freq, + self.missing_values == "ignore", + new_features, + ) - if self.drop_original: - X = X.drop(self.variables_, axis=1) + if self.drop_original is True: + X = drop_variables_from_df(X, self.variables_) - if self.drop_na: - X = X.dropna(subset=tmp.columns, axis=0) + if self.drop_na is True: + X = filter_rows(X, ~rows_with_missing_values(X, new_features)) - return X + return nw.to_native(X, pass_through=True) def _get_new_features_name(self) -> List: - """Get names of the window features.""" - - if not isinstance(self.functions, list): - functions_ = [self.functions] - else: - functions_ = self.functions - - feature_names = [ + """Get names of the expanding window features.""" + functions = ( + self.functions if isinstance(self.functions, list) else [self.functions] + ) + return [ f"{feature}_expanding_{agg}" for feature in self.variables_ - for agg in functions_ + for agg in functions ] - - return feature_names diff --git a/tests/test_time_series/test_forecasting/test_expanding_window_features.py b/tests/test_time_series/test_forecasting/test_expanding_window_features.py index 7126ed650..6238e95da 100644 --- a/tests/test_time_series/test_forecasting/test_expanding_window_features.py +++ b/tests/test_time_series/test_forecasting/test_expanding_window_features.py @@ -1,578 +1,471 @@ +import re + import numpy as np import pandas as pd +import polars as pl import pytest -from pandas.testing import assert_frame_equal from feature_engine.timeseries.forecasting import ExpandingWindowFeatures +from tests.backend_helpers import frame_to_dict, make_series +DATA = { + "x1": [3, 1, 4, 1, 5, 9], + "x2": [2.0, 7.0, 1.0, 8.0, 2.0, 8.0], + "color": ["a", "b", "c", "d", "e", "f"], +} -def test_get_feature_names_out_raises_when_input_features_is_string(df_time): - - tr = ExpandingWindowFeatures(functions=["mean", "sum"]) - tr.fit(df_time) - - with pytest.raises(ValueError): - # get error when user does not pass a list - tr.get_feature_names_out(input_features="ambient_temp") - - -def test_get_feature_names_out_raises_when_input_features_not_transformed(df_time): - - tr = ExpandingWindowFeatures(functions=["mean", "sum"]) - tr.fit(df_time) +DATES = pd.date_range("2020-05-15 12:00:00", periods=6, freq="15min") - with pytest.raises(ValueError): - # assert error when uses passes features that were not transformed - tr.get_feature_names_out(input_features=["color"]) +PANDAS_MAJOR = int(pd.__version__.split(".")[0]) +# pandas < 3 has no expanding first, last and nunique, and its sem divides by n - 1. +PANDAS_3_FUNCTIONS = ["first", "last", "nunique", "sem"] -@pytest.mark.parametrize("_periods", [1, 2, 3]) -def test_permitted_param_periods(_periods): - transformer = ExpandingWindowFeatures(periods=_periods) - assert transformer.periods == _periods - - -@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): - ExpandingWindowFeatures(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): - ExpandingWindowFeatures(drop_na=_drop_na) - +# init parameters +# the errors of the parameters from BaseForecastTransformer are tested in +# test_base_forecast_transformer.py +@pytest.mark.parametrize("min_periods", [-1, 1.5, "1", True, [1]]) +def test_error_if_min_periods_not_permitted(min_periods): + msg = ( + "min_periods must be None or a non-negative integer. " + f"Got {min_periods} instead." + ) + with pytest.raises(ValueError, match=re.escape(msg)): + ExpandingWindowFeatures(min_periods=min_periods) -def test_get_feature_names_out_multiple_variables_and_functions(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] - tr = ExpandingWindowFeatures(functions=["mean", "sum"]) - tr.fit(df_time) +@pytest.mark.parametrize( + "functions", [[np.min, np.max], np.min, 1, None, [], "", ["mean", 1], ("mean",)] +) +def test_error_if_functions_not_permitted(functions): + msg = ( + "functions must be a string or a non-empty list of strings. " + f"Got {functions} instead." + ) + with pytest.raises(ValueError, match=re.escape(msg)): + ExpandingWindowFeatures(functions=functions) + + +@pytest.mark.parametrize("functions", [["sum", "mean", "sum"], ["max", "max"]]) +def test_error_if_functions_duplicated(functions): + msg = f"There are duplicated functions in the list. Got {functions} instead." + with pytest.raises(ValueError, match=re.escape(msg)): + ExpandingWindowFeatures(functions=functions) + + +@pytest.mark.parametrize("periods", [-1, 1.5, "1", None, [1], True]) +def test_error_if_periods_not_permitted(periods): + msg = f"periods must be a non-negative integer. Got {periods} instead." + with pytest.raises(ValueError, match=re.escape(msg)): + ExpandingWindowFeatures(periods=periods) + + +@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)): + ExpandingWindowFeatures(sort_index=sort_index) + + +@pytest.mark.parametrize( + "min_periods, functions, periods, freq, sort_index, missing_values, " + "drop_original, drop_na", + [ + (None, "mean", 1, None, True, "raise", False, False), + (3, ["sum", "std"], 0, "15min", False, "ignore", True, True), + (0, ["max"], 2, "1h", True, "raise", False, True), + ], +) +def test_init_param_assignment( + min_periods, + functions, + periods, + freq, + sort_index, + missing_values, + drop_original, + drop_na, +): + transformer = ExpandingWindowFeatures( + min_periods=min_periods, + functions=functions, + periods=periods, + freq=freq, + sort_index=sort_index, + missing_values=missing_values, + drop_original=drop_original, + drop_na=drop_na, + ) + assert transformer.min_periods == min_periods + assert transformer.functions == functions + assert transformer.periods == periods + assert transformer.freq == freq + 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 +@pytest.mark.parametrize( + "variables, functions, expected", + [ + (None, "mean", ["x1_expanding_mean", "x2_expanding_mean"]), + ( + None, + ["mean", "sum"], + [ + "x1_expanding_mean", + "x1_expanding_sum", + "x2_expanding_mean", + "x2_expanding_sum", + ], + ), + ( + "x2", + ["sum", "mean", "count"], + ["x2_expanding_sum", "x2_expanding_mean", "x2_expanding_count"], + ), + ], +) +def test_get_feature_names_out(make_df, variables, functions, expected): + X = make_df(DATA) + transformer = ExpandingWindowFeatures(variables=variables, functions=functions) + transformer.fit(X) + original = ["x1", "x2", "color"] + + assert transformer.get_feature_names_out() == original + expected + assert transformer.get_feature_names_out(original) == original + expected + # with pandas, the columns are an Index, not a list + assert transformer.get_feature_names_out(X.columns) == original + expected + + +def test_get_feature_names_out_raises_error_if_input_features_not_list(make_df): + transformer = ExpandingWindowFeatures().fit(make_df(DATA)) + msg = "input_features must be a list or an array. Got x1 instead." + with pytest.raises(ValueError, match=re.escape(msg)): + transformer.get_feature_names_out(input_features="x1") + + +def test_get_feature_names_out_raises_error_if_input_features_not_in_fit(make_df): + transformer = ExpandingWindowFeatures().fit(make_df(DATA)) + 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"]) + + +def test_default_expanding_mean_of_all_numerical_variables(make_df): + X = make_df(DATA) + Xt = ExpandingWindowFeatures().fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "x1_expanding_mean": pytest.approx( + [None, 3.0, 2.0, 2.6666666666666665, 2.25, 2.8] + ), + "x2_expanding_mean": pytest.approx( + [None, 2.0, 4.5, 3.3333333333333335, 4.5, 4.0] + ), + } - # expected - output = [ - "ambient_temp_expanding_mean", - "ambient_temp_expanding_sum", - "module_temp_expanding_mean", - "module_temp_expanding_sum", - "irradiation_expanding_mean", - "irradiation_expanding_sum", - ] - output = original_features + output - assert tr.get_feature_names_out(input_features=None) == output - assert tr.get_feature_names_out(input_features=original_features) == output +@pytest.mark.parametrize( + "function, expected", + [ + ("count", [1.0, 2.0, 3.0, 4.0, 5.0]), + ("first", [2.0, 2.0, 2.0, 2.0, 2.0]), + ("kurt", [None, None, None, -5.211103, -2.897959]), + ("last", [2.0, 7.0, 1.0, 8.0, 2.0]), + ("max", [2.0, 7.0, 7.0, 8.0, 8.0]), + ("mean", [2.0, 4.5, 3.333333, 4.5, 4.0]), + ("median", [2.0, 4.5, 2.0, 4.5, 2.0]), + ("min", [2.0, 2.0, 1.0, 1.0, 1.0]), + ("nunique", [1.0, 2.0, 3.0, 4.0, 4.0]), + ("rank", [1.0, 2.0, 1.0, 4.0, 2.5]), + ("sem", [None, 2.5, 1.855921, 1.755942, 1.449138]), + ("skew", [None, None, 1.545393, 0.0, 0.587822]), + ("std", [None, 3.535534, 3.214550, 3.511885, 3.240370]), + ("sum", [2.0, 9.0, 10.0, 18.0, 20.0]), + ("var", [None, 12.5, 10.333333, 12.333333, 10.5]), + ], +) +def test_functions(make_df, function, expected): + if function in PANDAS_3_FUNCTIONS and make_df is pd.DataFrame and PANDAS_MAJOR < 3: + pytest.skip(f"{function} needs pandas 3") + X = make_df(DATA) + transformer = ExpandingWindowFeatures(variables="x2", functions=function) + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + # the first row has no past values + assert frame_to_dict(Xt)[f"x2_expanding_{function}"] == pytest.approx( + [None] + expected, abs=1e-6 + ) -def test_get_feature_names_out_single_variable_and_multiple_functions(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] - tr = ExpandingWindowFeatures( - variables="ambient_temp", functions=["sum", "mean", "count"] +@pytest.mark.parametrize( + "periods, expected", + [ + (0, [2.0, 9.0, 10.0, 18.0, 20.0, 28.0]), + (1, [None, 2.0, 9.0, 10.0, 18.0, 20.0]), + (3, [None, None, None, 2.0, 9.0, 10.0]), + ], +) +def test_periods(make_df, periods, expected): + X = make_df(DATA) + transformer = ExpandingWindowFeatures( + variables="x2", functions="sum", periods=periods ) - tr.fit(df_time) - - # expected - output = [ - "ambient_temp_expanding_sum", - "ambient_temp_expanding_mean", - "ambient_temp_expanding_count", - ] - output = original_features + output - assert tr.get_feature_names_out(input_features=None) == output - - -def test_get_feature_names_out_single_variable_and_single_function(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] - - tr = ExpandingWindowFeatures(variables="ambient_temp", functions="sum") - tr.fit(df_time) - - # expected - output = [ - "ambient_temp_expanding_sum", - ] - output = original_features + output - assert tr.get_feature_names_out(input_features=None) == output - - -def test_expanding_sum_single_var(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - np.nan, - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - 461.28, - ], - } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - - transformer = ExpandingWindowFeatures(variables=["ambient_temp"], functions="sum") - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) - - -def test_expanding_sum_multiple_vars(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - np.nan, - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - 461.28, - ], - "irradiation_expanding_sum": [ - np.nan, - 0.51, - 1.3, - 1.95, - 2.71, - 3.13, - 3.62, - 4.19, - 4.75, - 5.49, - 6.38, - 6.85, - 7.39, - 7.79, - 8.24, - ], - } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - expected_df["irradiation_expanding_sum"] = expected_results[ - "irradiation_expanding_sum" - ] - + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt)["x2_expanding_sum"] == expected + + +# NaN and inf are missing data for the statistics, but count includes inf. +DATA_NA = {"x": [None, 1.0, None, 4.0, np.inf, 9.0]} + + +@pytest.mark.parametrize( + "min_periods, expected", + [ + ( + None, + { + "x_expanding_count": [None, 0.0, 1.0, 1.0, 2.0, 3.0], + "x_expanding_sum": [None, 0.0, 1.0, 1.0, 5.0, 5.0], + "x_expanding_mean": [None, None, 1.0, 1.0, 2.5, 2.5], + "x_expanding_min": [None, None, 1.0, 1.0, 1.0, 1.0], + "x_expanding_std": pytest.approx( + [None, None, None, None, 2.1213203435596424, 2.1213203435596424] + ), + }, + ), + ( + 2, + { + "x_expanding_count": [None, None, 1.0, 1.0, 2.0, 3.0], + "x_expanding_sum": [None, None, None, None, 5.0, 5.0], + "x_expanding_mean": [None, None, None, None, 2.5, 2.5], + "x_expanding_min": [None, None, None, None, 1.0, 1.0], + "x_expanding_std": pytest.approx( + [None, None, None, None, 2.1213203435596424, 2.1213203435596424] + ), + }, + ), + ], +) +def test_min_periods_and_missing_data(make_df, min_periods, expected): + X = make_df(DATA_NA) transformer = ExpandingWindowFeatures( - variables=["ambient_temp", "irradiation"], functions="sum" + functions=["count", "sum", "mean", "min", "std"], + min_periods=min_periods, + missing_values="ignore", ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) - - -def test_expanding_sum_and_mean_single_var(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - np.nan, - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - 461.28, - ], - "ambient_temp_expanding_mean": [ - np.nan, - 31.3100, - 31.4100, - 31.6567, - 31.8400, - 31.9960, - 32.0800, - 32.1429, - 32.2100, - 32.3822, - 32.5570, - 32.6955, - 32.7792, - 32.8646, - 32.9486, - ], - } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - expected_df["ambient_temp_expanding_mean"] = expected_results[ - "ambient_temp_expanding_mean" - ] - + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == {**DATA_NA, **expected} + + +@pytest.mark.parametrize( + "function, min_periods, expected", + [ + ("first", None, [None, None, 1.0, 1.0, 1.0, 1.0]), + ("first", 2, [None, None, None, None, 1.0, 1.0]), + ("last", None, [None, None, 1.0, 1.0, 4.0, 4.0]), + ("last", 2, [None, None, None, None, 4.0, 4.0]), + # like the sum, nunique is 0 before the first value + ("nunique", None, [None, 0.0, 1.0, 1.0, 2.0, 2.0]), + ("nunique", 2, [None, None, None, None, 2.0, 2.0]), + # the last past value is missing, so it has no rank + ("rank", None, [None, None, 1.0, None, 2.0, None]), + ("rank", 2, [None, None, None, None, 2.0, None]), + # inf is missing data for the std, but pandas counts it in the number of values + ("sem", None, [None, None, None, None, 1.5, 1.224745]), + ("sem", 2, [None, None, None, None, 1.5, 1.224745]), + ], +) +def test_functions_with_missing_data(make_df, function, min_periods, expected): + if function in PANDAS_3_FUNCTIONS and make_df is pd.DataFrame and PANDAS_MAJOR < 3: + pytest.skip(f"{function} needs pandas 3") + X = make_df(DATA_NA) transformer = ExpandingWindowFeatures( - variables=["ambient_temp"], functions=["sum", "mean"] + functions=function, min_periods=min_periods, missing_values="ignore" ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) - - -def test_expanding_sum_and_mean_multiple_vars(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - np.nan, - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - 461.28, - ], - "ambient_temp_expanding_mean": [ - np.nan, - 31.3100, - 31.4100, - 31.6567, - 31.8400, - 31.9960, - 32.0800, - 32.1429, - 32.2100, - 32.3822, - 32.5570, - 32.6955, - 32.7792, - 32.8646, - 32.9486, - ], - "irradiation_expanding_sum": [ - np.nan, - 0.51, - 1.3, - 1.95, - 2.71, - 3.13, - 3.62, - 4.19, - 4.75, - 5.49, - 6.38, - 6.85, - 7.39, - 7.79, - 8.24, - ], - "irradiation_expanding_mean": [ - np.nan, - 0.51000, - 0.65000, - 0.65000, - 0.67750, - 0.62600, - 0.60333, - 0.59857, - 0.59375, - 0.61000, - 0.63800, - 0.62273, - 0.61583, - 0.59923, - 0.58857, - ], - } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - expected_df["ambient_temp_expanding_mean"] = expected_results[ - "ambient_temp_expanding_mean" - ] - expected_df["irradiation_expanding_sum"] = expected_results[ - "irradiation_expanding_sum" - ] - expected_df["irradiation_expanding_mean"] = expected_results[ - "irradiation_expanding_mean" - ] + Xt = transformer.fit_transform(X) + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt)[f"x_expanding_{function}"] == pytest.approx( + expected, abs=1e-6 + ) + + +def test_nan_is_missing_data(make_df): + # polars keeps NaN apart from null, pandas treats both as missing data. + X = make_df({"x": [1.0, np.nan, 3.0, 5.0]}) transformer = ExpandingWindowFeatures( - variables=["ambient_temp", "irradiation"], functions=["sum", "mean"] + functions=["count", "mean", "max"], missing_values="ignore" ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) - - -def test_expanding_sum_single_var_periods(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - np.nan, - np.nan, - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - ], + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "x": [1.0, None, 3.0, 5.0], + "x_expanding_count": [None, 1.0, 1.0, 2.0], + "x_expanding_mean": [None, 1.0, 1.0, 2.0], + "x_expanding_max": [None, 1.0, 1.0, 3.0], + } + + +def test_drop_original(make_df): + X = make_df(DATA) + transformer = ExpandingWindowFeatures(functions=["min", "max"], drop_original=True) + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + # the dicts below don't check the order of the columns + assert list(Xt.columns) == transformer.get_feature_names_out() + assert frame_to_dict(Xt) == { + "color": DATA["color"], + "x1_expanding_min": [None, 3.0, 1.0, 1.0, 1.0, 1.0], + "x1_expanding_max": [None, 3.0, 3.0, 4.0, 4.0, 5.0], + "x2_expanding_min": [None, 2.0, 2.0, 1.0, 1.0, 1.0], + "x2_expanding_max": [None, 2.0, 7.0, 7.0, 8.0, 8.0], } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] + +def test_drop_na(make_df): + X = make_df(DATA) transformer = ExpandingWindowFeatures( - variables=["ambient_temp"], functions="sum", periods=2 + variables="x1", functions=["sum", "std"], drop_na=True ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) - - -def test_expanding_sum_single_var_freqs(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - np.nan, - np.nan, - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - ], + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "x1": [4, 1, 5, 9], + "x2": [1.0, 8.0, 2.0, 8.0], + "color": ["c", "d", "e", "f"], + "x1_expanding_sum": [4.0, 8.0, 9.0, 14.0], + "x1_expanding_std": pytest.approx( + [1.4142135623730951, 1.5275252316519468, 1.5, 1.7888543819998317] + ), } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] + +def test_drop_original_and_drop_na(make_df): + X = make_df(DATA) transformer = ExpandingWindowFeatures( - variables=["ambient_temp"], functions="sum", freq="30min" + functions="std", drop_original=True, drop_na=True ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) - - -def test_expanding_sum_single_var_periods_and_freqs(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - np.nan, - np.nan, - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - ], + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "color": ["c", "d", "e", "f"], + "x1_expanding_std": pytest.approx([1.414214, 1.527525, 1.5, 1.788854]), + "x2_expanding_std": pytest.approx([3.535534, 3.214550, 3.511885, 3.240370]), } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] + +@pytest.mark.parametrize( + "drop_na, expected", [(True, [3, 4, 5, 6]), (False, [1, 2, 3, 4, 5, 6])] +) +def test_transform_x_y(make_df, drop_na, expected): + X = make_df(DATA) + y = make_series(make_df, [1, 2, 3, 4, 5, 6], name="y") transformer = ExpandingWindowFeatures( - variables=["ambient_temp"], functions="sum", periods=2, freq="15min" + variables="x1", functions=["sum", "std"], drop_na=drop_na + ).fit(X) + + Xt, yt = transformer.transform_x_y(X, y) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == frame_to_dict(transformer.transform(X)) + assert list(yt) == expected + + +@pytest.mark.parametrize("y", [[1, 2, 3, 4, 5, 6], np.array([1, 2, 3, 4, 5, 6])]) +def test_fit_accepts_y_as_list_and_array(make_df, y): + X = make_df(DATA) + Xt = ExpandingWindowFeatures(variables="x1").fit(X, y).transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt)["x1_expanding_mean"] == pytest.approx( + [None, 3.0, 2.0, 2.6666666666666665, 2.25, 2.8] ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) -def test_sort_index(df_time): - # Shuffle dataframe - Xs = df_time.sample(frac=1) +def test_no_numerical_variables_with_return_empty(make_df): + X = make_df({"color": DATA["color"]}) + Xt = ExpandingWindowFeatures(return_empty=True).fit_transform(X) - transformer = ExpandingWindowFeatures(sort_index=False) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal(df_tr[transformer.variables_], Xs[transformer.variables_]) + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == {"color": DATA["color"]} - transformer = ExpandingWindowFeatures(sort_index=True) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal( - df_tr[transformer.variables_], Xs[transformer.variables_].sort_index() + +# pandas: the index orders the rows in time, and freq shifts the index +@pytest.mark.parametrize( + "periods, freq", + [(1, "30min"), (2, "15min"), (2, None)], +) +def test_freq_with_pandas(periods, freq): + X = pd.DataFrame(DATA, index=DATES) + transformer = ExpandingWindowFeatures( + variables="x2", functions="sum", periods=periods, freq=freq ) + Xt = transformer.fit_transform(X) + expected = X.assign(x2_expanding_sum=[np.nan, np.nan, 2.0, 9.0, 10.0, 18.0]) + pd.testing.assert_frame_equal(Xt, expected) -def test_expanding_window_raises_when_periods_negative(): - with pytest.raises( - ValueError, match="periods must be a non-negative integer. Got -1 instead." - ): - ExpandingWindowFeatures(periods=-1) - - -def test_drop_na(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - 461.28, - ], - "irradiation_expanding_sum": [ - 0.51, - 1.3, - 1.95, - 2.71, - 3.13, - 3.62, - 4.19, - 4.75, - 5.49, - 6.38, - 6.85, - 7.39, - 7.79, - 8.24, - ], - } - expected_df = df_time.iloc[1:].copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - expected_df["irradiation_expanding_sum"] = expected_results[ - "irradiation_expanding_sum" - ] + +def test_sort_index_with_pandas(): + X = pd.DataFrame(DATA, index=DATES).iloc[[3, 0, 5, 1, 4, 2]] + + Xt = ExpandingWindowFeatures(variables="x2", functions="max").fit_transform(X) + expected = X.sort_index().assign(x2_expanding_max=[np.nan, 2.0, 7.0, 7.0, 8.0, 8.0]) + pd.testing.assert_frame_equal(Xt, expected) transformer = ExpandingWindowFeatures( - variables=["ambient_temp", "irradiation"], - functions="sum", - drop_na=True, + variables="x2", functions="max", sort_index=False ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) - - -def test_transform_x_y(df_time): - y = pd.Series(np.zeros(len(df_time)), index=df_time.index) - expected_results = { - "ambient_temp_expanding_sum": [ - 31.31, - 62.82, - 94.97, - 127.36, - 159.98, - 192.48, - 225.00, - 257.68, - 291.44, - 325.57, - 359.65, - 393.35, - 427.24, - 461.28, - ], - "irradiation_expanding_sum": [ - 0.51, - 1.3, - 1.95, - 2.71, - 3.13, - 3.62, - 4.19, - 4.75, - 5.49, - 6.38, - 6.85, - 7.39, - 7.79, - 8.24, - ], - } - expected_df = df_time.iloc[1:].copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - expected_df["irradiation_expanding_sum"] = expected_results[ - "irradiation_expanding_sum" - ] + Xt = transformer.fit_transform(X) + expected = X.assign(x2_expanding_max=[np.nan, 8.0, 8.0, 8.0, 8.0, 8.0]) + pd.testing.assert_frame_equal(Xt, expected) + +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 = ExpandingWindowFeatures( - variables=["ambient_temp", "irradiation"], - functions="sum", - drop_na=True, + functions=["mean", "max"], drop_original=True, drop_na=True + ).fit(X) + Xt = transformer.transform(X[["c", 1, 0]]) + + expected = pd.DataFrame( + { + "c": ["y", "z"], + "0_expanding_mean": [1.0, 1.5], + "0_expanding_max": [1.0, 2.0], + "1_expanding_mean": [4.0, 4.5], + "1_expanding_max": [4.0, 5.0], + }, + index=[1, 2], + ) + # the columns started as a mix of integers and strings + expected.columns = expected.columns.astype(object) + pd.testing.assert_frame_equal(Xt, expected) + + +# polars: the functions that polars supports +@pytest.mark.parametrize("functions", ["quantile", ["mean", "prod"]]) +def test_error_if_function_not_supported_with_polars(functions): + msg = ( + "With dataframes other than pandas, functions takes only ['count', 'first', " + "'kurt', 'last', 'max', 'mean', 'median', 'min', 'nunique', 'rank', 'sem', " + f"'skew', 'std', 'sum', 'var']. Got {functions} instead." ) - transformer.fit(df_time) - - Xt, yt = transformer.transform_x_y(df_time, y) - assert len(Xt) == len(yt) - assert len(y) != len(yt) - assert (Xt.index == yt.index).all() - - -def test_error_duplicate_functions(df_time): - msg = "There are duplicated functions in the list: ['sum', 'sum']" - with pytest.raises(ValueError) as record: - ExpandingWindowFeatures( - variables=["ambient_temp"], functions=["sum", "sum"], periods=2, freq="15T" - ) - - # check that error message matches - assert str(record.value) == msg - - -@pytest.mark.parametrize("functions", [[np.min, np.max], np.min]) -def test_error_native_functions(df_time, functions): - msg = "functions must be a list of strings or a string." f"Got {functions} instead." - with pytest.raises(ValueError) as record: - ExpandingWindowFeatures( - variables=["ambient_temp"], - functions=functions, - periods=2, - freq="15T", - ) - - # check that error message matches - assert str(record.value) == msg + with pytest.raises(NotImplementedError, match=re.escape(msg)): + ExpandingWindowFeatures(functions=functions).fit(pl.DataFrame(DATA)) 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 164eca5dc..86eba078a 100644 --- a/tests/test_time_series/test_forecasting/test_forecasting_helpers.py +++ b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py @@ -7,8 +7,10 @@ from feature_engine.dataframe_checks import check_X from feature_engine.timeseries.forecasting._forecasting_helpers import ( + add_expanding_window_features, add_lag_features, add_window_features, + check_functions_supported, check_index, check_window_parameters, sort_by_index, @@ -136,3 +138,32 @@ def test_check_window_parameters_accepts_everything_with_pandas( ): X = check_X(pd.DataFrame({"a": [1, 2, 3]}, index=DATES)) check_window_parameters(X, window, functions, min_periods) + + +def test_add_expanding_window_features(make_df): + X = check_X(make_df({"a": [1.0, 3.0, 2.0, 4.0]})) + names = ["a_max", "a_median", "a_sum"] + Xt = add_expanding_window_features( + X, ["a"], ["max", "median", "sum"], None, 1, None, False, names + ) + + # with polars, the median is a polars series among narwhals expressions + assert list(Xt.columns) == ["a"] + names + assert frame_to_dict(nw.to_native(Xt, pass_through=True)) == { + "a": [1.0, 3.0, 2.0, 4.0], + "a_max": [None, 1.0, 3.0, 3.0], + "a_median": [None, 1.0, 2.0, 2.0], + "a_sum": [None, 1.0, 4.0, 6.0], + } + + +def test_check_functions_supported(): + check_functions_supported(check_X(pd.DataFrame({"a": [1]})), ["quantile"]) + + msg = ( + "With dataframes other than pandas, functions takes only ['count', 'first', " + "'kurt', 'last', 'max', 'mean', 'median', 'min', 'nunique', 'rank', 'sem', " + "'skew', 'std', 'sum', 'var']. Got quantile instead." + ) + with pytest.raises(NotImplementedError, match=re.escape(msg)): + check_functions_supported(check_X(pl.DataFrame({"a": [1]})), "quantile")