From c3c9303b0ea031652588c989df6ee48a45d66e7f Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Sat, 19 Sep 2026 11:42:22 +0200 Subject: [PATCH 1/3] Migrate ExpandingWindowFeatures to narwhals, add polars support pandas keeps its expanding().agg().shift() path. With polars, the features are built with narwhals rolling and cumulative expressions, and the polars rolling median, and give the same values as pandas. Co-Authored-By: Claude Opus 5 --- .../forecasting/ExpandingWindowFeatures.rst | 90 +- .../forecasting/expanding_window_features.py | 194 +++- .../test_expanding_window_features.py | 882 ++++++++---------- 3 files changed, 592 insertions(+), 574 deletions(-) diff --git a/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst b/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst index 3d8714a67..c3c919fa3 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,20 @@ 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 operation +supported by pandas. For supported aggregation functions, see Expanding Window `Functions `_. -With `pandas.shift`, :class:`ExpandingWindowFeatures` lags the result of the expanding +With polars dataframes, :class:`ExpandingWindowFeatures` supports the functions `"count"`, +`"sum"`, `"mean"`, `"median"`, `"min"`, `"max"`, `"std"` and `"var"`, and returns the +same values as pandas. + +: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 +85,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 +373,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 @@ -424,6 +431,67 @@ The original variable is no longer in the output dataframe: 2020-05-15 12:45:00 31.656667 32.15 2020-05-15 13:00:00 31.840000 32.39 +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 │ + └──────────────────┴──────────────┴─────────────────────────────┴────────────────────────────┘ + +With polars, other functions, like `"skew"`, raise an error: + +.. code:: python + + ExpandingWindowFeatures(functions=["skew"]).fit_transform(X) + +.. code:: text + + NotImplementedError: With dataframes other than pandas, ExpandingWindowFeatures supports the functions ['count', 'sum', 'mean', 'median', 'min', 'max', 'std', 'var']. Got ['skew'] instead. + Getting the name of the new features ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/feature_engine/timeseries/forecasting/expanding_window_features.py b/feature_engine/timeseries/forecasting/expanding_window_features.py index c121734e1..d9f467e5d 100644 --- a/feature_engine/timeseries/forecasting/expanding_window_features.py +++ b/feature_engine/timeseries/forecasting/expanding_window_features.py @@ -5,7 +5,9 @@ from typing import List -import pandas as pd +import narwhals as nw +import narwhals.dependencies as nwd +from narwhals.typing import IntoDataFrame from feature_engine._docstrings.fit_attributes import ( _feature_names_in_docstring, @@ -26,6 +28,9 @@ BaseForecastTransformer, ) +# functions supported with dataframes other than pandas. +_FUNCTIONS = ["count", "sum", "mean", "median", "min", "max", "std", "var"] + @Substitution( variables=_variables_numerical_docstring, @@ -47,17 +52,23 @@ 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. + With polars, ExpandingWindowFeatures supports the functions 'count', 'sum', + 'mean', 'median', 'min', 'max', 'std' and 'var', and returns the same values + as pandas. 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 +85,26 @@ 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 `_. + The functions to apply within the window. With pandas, valid functions can be + found `here `_. With + polars, the functions can be 'count', 'sum', 'mean', 'median', 'min', 'max', + 'std' and 'var'. - periods: int, list of ints, default=1 - Number of periods to shift. Can be a positive integer. See param `periods` in - pandas `shift`. + periods: int, default=1 + Number of periods to shift. Can be zero or a positive integer. See param + `periods` in pandas `shift`. - freq: str, list of str, default=None + 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 +163,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,11 +206,13 @@ def __init__( drop_na: bool = False, ) -> None: - if not isinstance(functions, (str, list)) or not all( - isinstance(val, str) for val in functions + 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 list of strings or a string. " f"Got {functions} instead." ) if isinstance(functions, list) and len(functions) != len(set(functions)): @@ -191,54 +233,108 @@ def __init__( self.freq = freq self.sort_index = sort_index - def transform(self, X: pd.DataFrame) -> pd.DataFrame: + 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] + X_new: dataframe of shape = [n_samples, n_features + window_features] The dataframe with the original plus the new variables. """ - # 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") - - if self.drop_original: - X = X.drop(self.variables_, axis=1) - - if self.drop_na: - X = X.dropna(subset=tmp.columns, axis=0) + return super().transform(X) + + def _add_features(self, nw_X: nw.DataFrame) -> nw.DataFrame: + """Add the expanding window features after the columns of nw_X.""" + X = nw_X.to_native() + if nwd.is_pandas_dataframe(X) is True: + # pandas is faster than narwhals, and freq shifts the pandas index. + 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") + return nw.from_native(X, eager_only=True) + + functions = self._functions_list() + unsupported = [func for func in functions if func not in _FUNCTIONS] + if len(unsupported) > 0: + raise NotImplementedError( + "With dataframes other than pandas, ExpandingWindowFeatures supports " + f"the functions {_FUNCTIONS}. Got {unsupported} instead." + ) - return X + # pandas treats min_periods=None as 0. narwhals' rolling functions need at + # least 1, and 0 only changes the sum, done below. + min_periods = 0 if self.min_periods is None else self.min_periods + min_samples = max(min_periods, 1) + # a rolling window as long as the dataframe is an expanding window. + window = max(len(nw_X), min_samples) + + new_features = [] + for var in self.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 self.missing_values == "ignore": + 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() + for func in functions: + 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 in ("min", "max"): + # cumulative min and max are faster than rolling ones, but + # they are null in the rows with missing data. + cum = x.cum_min() if func == "min" else x.cum_max() + feature = nw.when(count >= min_samples).then( + cum.fill_null(strategy="forward") + ) + elif func == "median": + # narwhals has no rolling median: use the polars series. + values = nw_X.select(x).get_column(var).to_native() + feature = nw.from_native( + values.rolling_median(window, min_samples=min_samples), + series_only=True, + ) + else: + feature = getattr(x, f"rolling_{func}")( + window, min_samples=min_samples + ) + if func == "sum" and min_periods == 0: + feature = feature.fill_null(0) + new_features.append( + feature.shift(self.periods).alias(f"{var}_expanding_{func}") + ) + + return nw_X.with_columns(new_features) + + def _functions_list(self) -> List[str]: + """Return the functions as a list.""" + if isinstance(self.functions, list): + return self.functions + return [self.functions] 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 = [ f"{feature}_expanding_{agg}" for feature in self.variables_ - for agg in functions_ + for agg in self._functions_list() ] 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..ad912981c 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,432 @@ +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"], +} + +DATES = pd.date_range("2020-05-15 12:00:00", periods=6, freq="15min") + + +# init parameters +# the errors of the parameters from BaseForecastTransformer are tested in +# test_base_forecast_transformer.py +@pytest.mark.parametrize( + "functions", [[np.min, np.max], np.min, 1, None, [], "", ["mean", 1], ("mean",)] +) +def test_error_if_functions_not_permitted(functions): + msg = f"functions must be a list of strings or a string. Got {functions} instead." + with pytest.raises(ValueError, match=re.escape(msg)): + ExpandingWindowFeatures(functions=functions) + + +def test_error_if_functions_duplicated(): + msg = "There are duplicated functions in the list: ['sum', 'mean', 'sum']" + with pytest.raises(ValueError, match=re.escape(msg)): + ExpandingWindowFeatures(functions=["sum", "mean", "sum"]) + + +@pytest.mark.parametrize("periods", [-1, 1.5, "1", None, [1]]) +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( + "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), + (1, ["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): + transformer = ExpandingWindowFeatures(variables=variables, functions=functions) + transformer.fit(make_df(DATA)) + + assert transformer.get_feature_names_out() == ["x1", "x2", "color"] + expected + assert ( + transformer.get_feature_names_out(["x1", "x2", "color"]) + == [ + "x1", + "x2", + "color", + ] + + expected + ) -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_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_when_input_features_not_transformed(df_time): +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"]) - tr = ExpandingWindowFeatures(functions=["mean", "sum"]) - tr.fit(df_time) - with pytest.raises(ValueError): - # assert error when uses passes features that were not transformed - tr.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] + ), + } -@pytest.mark.parametrize("_periods", [1, 2, 3]) -def test_permitted_param_periods(_periods): - transformer = ExpandingWindowFeatures(periods=_periods) - assert transformer.periods == _periods +def test_all_functions_supported_with_polars(make_df): + functions = ["count", "sum", "mean", "median", "min", "max", "std", "var"] + X = make_df(DATA) + Xt = ExpandingWindowFeatures(variables="x2", functions=functions).fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "x2_expanding_count": [None, 1.0, 2.0, 3.0, 4.0, 5.0], + "x2_expanding_sum": [None, 2.0, 9.0, 10.0, 18.0, 20.0], + "x2_expanding_mean": pytest.approx( + [None, 2.0, 4.5, 3.3333333333333335, 4.5, 4.0] + ), + "x2_expanding_median": [None, 2.0, 4.5, 2.0, 4.5, 2.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], + "x2_expanding_std": pytest.approx( + [ + None, + None, + 3.5355339059327378, + 3.214550253664318, + 3.5118845842842465, + 3.24037034920393, + ] + ), + "x2_expanding_var": pytest.approx( + [None, None, 12.5, 10.333333333333332, 12.333333333333334, 10.5] + ), + } -@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( + "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 + ) + 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( + functions=["count", "sum", "mean", "min", "std"], + min_periods=min_periods, + missing_values="ignore", + ) + Xt = transformer.fit_transform(X) -@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) + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == {**DATA_NA, **expected} -def test_get_feature_names_out_multiple_variables_and_functions(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] +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( + functions=["count", "mean", "max"], missing_values="ignore" + ) + 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], + } - tr = ExpandingWindowFeatures(functions=["mean", "sum"]) - tr.fit(df_time) - # 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 +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) + 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], + } -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"] +def test_drop_na(make_df): + X = make_df(DATA) + transformer = ExpandingWindowFeatures( + variables="x1", functions=["sum", "std"], drop_na=True ) - tr.fit(df_time) + 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 - 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 +@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="x1", functions=["sum", "std"], drop_na=drop_na + ).fit(X) + Xt, yt = transformer.transform_x_y(X, y) -def test_get_feature_names_out_single_variable_and_single_function(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == frame_to_dict(transformer.transform(X)) + assert list(yt) == expected - 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 +@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] + ) -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_no_numerical_variables_with_return_empty(make_df): + X = make_df({"color": DATA["color"]}) + Xt = ExpandingWindowFeatures(return_empty=True).fit_transform(X) + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == {"color": DATA["color"]} -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" - ] +# 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=["ambient_temp", "irradiation"], functions="sum" + variables="x2", functions="sum", periods=periods, freq=freq ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) + 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_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" - ] - transformer = ExpandingWindowFeatures( - variables=["ambient_temp"], functions=["sum", "mean"] - ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) +def test_sort_index_with_pandas(): + X = pd.DataFrame(DATA, index=DATES).iloc[[3, 0, 5, 1, 4, 2]] - -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 = 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", "mean"] + variables="x2", functions="max", sort_index=False ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) + 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_expanding_sum_single_var_periods(df_time): - expected_results = { - "ambient_temp_expanding_sum": [ +def test_functions_not_supported_by_polars_with_pandas(): + X = pd.DataFrame(DATA) + transformer = ExpandingWindowFeatures(variables="x2", functions=["skew", "sem"]) + Xt = transformer.fit_transform(X) + + expected = X.assign( + x2_expanding_skew=[ + np.nan, 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, + 1.545392525695021, + 0.0, + 0.5878222855698739, ], - } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - - transformer = ExpandingWindowFeatures( - variables=["ambient_temp"], functions="sum", periods=2 - ) - 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": [ + x2_expanding_sem=[ 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, + 2.5, + 1.855921454276674, + 1.7559422921421233, + 1.4491376746189437, ], - } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - - transformer = ExpandingWindowFeatures( - variables=["ambient_temp"], functions="sum", freq="30min" ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) + pd.testing.assert_frame_equal(Xt, expected) -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, - ], - } - expected_df = df_time.copy() - expected_df["ambient_temp_expanding_sum"] = expected_results[ - "ambient_temp_expanding_sum" - ] - +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"], functions="sum", periods=2, freq="15min" + 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], ) - df_tr = transformer.fit_transform(df_time) - assert_frame_equal(df_tr, expected_df) + # the columns started as a mix of integers and strings + expected.columns = expected.columns.astype(object) + pd.testing.assert_frame_equal(Xt, expected) -def test_sort_index(df_time): - # Shuffle dataframe - Xs = df_time.sample(frac=1) - - transformer = ExpandingWindowFeatures(sort_index=False) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal(df_tr[transformer.variables_], Xs[transformer.variables_]) - - transformer = ExpandingWindowFeatures(sort_index=True) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal( - df_tr[transformer.variables_], Xs[transformer.variables_].sort_index() - ) - +# polars: the rows are used in the order given +def test_rows_are_used_in_the_order_given_with_polars(): + X = pl.DataFrame({"x": [8.0, 2.0, 7.0, 1.0]}) + Xt = ExpandingWindowFeatures(functions="min", sort_index=True).fit_transform(X) -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" - ] + assert frame_to_dict(Xt)["x_expanding_min"] == [None, 8.0, 2.0, 2.0] - transformer = ExpandingWindowFeatures( - variables=["ambient_temp", "irradiation"], - functions="sum", - drop_na=True, - ) - 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" - ] - transformer = ExpandingWindowFeatures( - variables=["ambient_temp", "irradiation"], - functions="sum", - drop_na=True, +def test_error_if_function_not_supported_with_polars(): + X = pl.DataFrame(DATA) + transformer = ExpandingWindowFeatures(functions=["mean", "skew", "sem"]).fit(X) + msg = ( + "With dataframes other than pandas, ExpandingWindowFeatures supports the " + "functions ['count', 'sum', 'mean', 'median', 'min', 'max', 'std', 'var']. " + "Got ['skew', 'sem'] 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)): + transformer.transform(X) From 648028d4dc046925d1153b433667e253e65d3829 Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Sat, 21 Nov 2026 10:24:48 +0100 Subject: [PATCH 2/3] move ExpandingWindowFeatures to check_X and the forecasting helpers Co-Authored-By: Claude Opus 5.5 --- .../forecasting/ExpandingWindowFeatures.rst | 2 +- .../forecasting/_forecasting_helpers.py | 137 ++++++++++++++++++ .../forecasting/expanding_window_features.py | 124 +++++++--------- .../test_expanding_window_features.py | 12 +- .../test_forecasting_helpers.py | 30 ++++ 5 files changed, 223 insertions(+), 82 deletions(-) diff --git a/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst b/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst index c3c919fa3..2084f073c 100644 --- a/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst +++ b/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst @@ -490,7 +490,7 @@ With polars, other functions, like `"skew"`, raise an error: .. code:: text - NotImplementedError: With dataframes other than pandas, ExpandingWindowFeatures supports the functions ['count', 'sum', 'mean', 'median', 'min', 'max', 'std', 'var']. Got ['skew'] instead. + NotImplementedError: With dataframes other than pandas, functions takes only ['count', 'max', 'mean', 'median', 'min', 'std', 'sum', 'var']. Got ['skew'] instead. Getting the name of the new features ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/feature_engine/timeseries/forecasting/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index e3487ea77..a287b4dff 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -198,6 +198,35 @@ def add_lag_features( return X +def check_functions_supported( + X: DataFrame, functions: Union[str, List[str]], supported: 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. + + supported : list + The functions supported with dataframes other than pandas. + """ + # pandas supports every function. + if not isinstance(X, nw.DataFrame): + return + + function_list = functions if isinstance(functions, list) else [functions] + if not all(function in supported for function in function_list): + raise NotImplementedError( + "With dataframes other than pandas, functions takes only " + f"{sorted(supported)}. Got {functions} instead." + ) + + def check_window_parameters( X: DataFrame, window: Any, @@ -341,3 +370,111 @@ 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 + return X.merge(tmp, left_index=True, right_index=True, how="left") + + # pandas treats min_periods=None as 0. narwhals' rolling functions need at + # least 1, and 0 only changes the 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() + 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 in ("min", "max"): + # cumulative min and max are faster than rolling ones, but + # they are null in the rows with missing data. + cum = x.cum_min() if func == "min" else x.cum_max() + feature = nw.when(count >= min_samples).then( + cum.fill_null(strategy="forward") + ) + elif func == "median": + # narwhals has no rolling median: use the polars series. + values = X.select(x).get_column(var).to_native() + feature = nw.from_native( + values.rolling_median(window, min_samples=min_samples), + series_only=True, + ) + else: + feature = getattr(x, f"rolling_{func}")( + window, min_samples=min_samples + ) + if func == "sum" and min_periods == 0: + feature = feature.fill_null(0) + new_features.append(feature.shift(periods)) + + return X.with_columns( + feature.alias(name) for feature, name in zip(new_features, names) + ) diff --git a/feature_engine/timeseries/forecasting/expanding_window_features.py b/feature_engine/timeseries/forecasting/expanding_window_features.py index d9f467e5d..3aa67e390 100644 --- a/feature_engine/timeseries/forecasting/expanding_window_features.py +++ b/feature_engine/timeseries/forecasting/expanding_window_features.py @@ -6,8 +6,7 @@ from typing import List import narwhals as nw -import narwhals.dependencies as nwd -from narwhals.typing import IntoDataFrame +from narwhals.typing import IntoDataFrame, IntoSeries from feature_engine._docstrings.fit_attributes import ( _feature_names_in_docstring, @@ -24,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, ) @@ -233,6 +242,22 @@ def __init__( self.freq = freq self.sort_index = sort_index + 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, _FUNCTIONS) + return self + def transform(self, X: IntoDataFrame) -> IntoDataFrame: """ Adds expanding window features. @@ -245,82 +270,31 @@ def transform(self, X: IntoDataFrame) -> IntoDataFrame: Returns ------- X_new: dataframe of shape = [n_samples, n_features + window_features] - The dataframe with the original plus the new variables. + The dataframe with the original plus the new variables. If + `drop_na=True`, rows with missing data in the new features are removed. """ - return super().transform(X) - - def _add_features(self, nw_X: nw.DataFrame) -> nw.DataFrame: - """Add the expanding window features after the columns of nw_X.""" - X = nw_X.to_native() - if nwd.is_pandas_dataframe(X) is True: - # pandas is faster than narwhals, and freq shifts the pandas index. - 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") - return nw.from_native(X, eager_only=True) - - functions = self._functions_list() - unsupported = [func for func in functions if func not in _FUNCTIONS] - if len(unsupported) > 0: - raise NotImplementedError( - "With dataframes other than pandas, ExpandingWindowFeatures supports " - f"the functions {_FUNCTIONS}. Got {unsupported} instead." + X = self._check_transform_input_and_state(X) + + 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, ) - # pandas treats min_periods=None as 0. narwhals' rolling functions need at - # least 1, and 0 only changes the sum, done below. - min_periods = 0 if self.min_periods is None else self.min_periods - min_samples = max(min_periods, 1) - # a rolling window as long as the dataframe is an expanding window. - window = max(len(nw_X), min_samples) - - new_features = [] - for var in self.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 self.missing_values == "ignore": - 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() - for func in functions: - 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 in ("min", "max"): - # cumulative min and max are faster than rolling ones, but - # they are null in the rows with missing data. - cum = x.cum_min() if func == "min" else x.cum_max() - feature = nw.when(count >= min_samples).then( - cum.fill_null(strategy="forward") - ) - elif func == "median": - # narwhals has no rolling median: use the polars series. - values = nw_X.select(x).get_column(var).to_native() - feature = nw.from_native( - values.rolling_median(window, min_samples=min_samples), - series_only=True, - ) - else: - feature = getattr(x, f"rolling_{func}")( - window, min_samples=min_samples - ) - if func == "sum" and min_periods == 0: - feature = feature.fill_null(0) - new_features.append( - feature.shift(self.periods).alias(f"{var}_expanding_{func}") - ) - - return nw_X.with_columns(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 _functions_list(self) -> List[str]: """Return the functions as a list.""" 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 ad912981c..c72f5ad0d 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 @@ -421,12 +421,12 @@ def test_rows_are_used_in_the_order_given_with_polars(): def test_error_if_function_not_supported_with_polars(): - X = pl.DataFrame(DATA) - transformer = ExpandingWindowFeatures(functions=["mean", "skew", "sem"]).fit(X) msg = ( - "With dataframes other than pandas, ExpandingWindowFeatures supports the " - "functions ['count', 'sum', 'mean', 'median', 'min', 'max', 'std', 'var']. " - "Got ['skew', 'sem'] instead." + "With dataframes other than pandas, functions takes only " + "['count', 'max', 'mean', 'median', 'min', 'std', 'sum', 'var']. " + "Got ['mean', 'skew', 'sem'] instead." ) with pytest.raises(NotImplementedError, match=re.escape(msg)): - transformer.transform(X) + ExpandingWindowFeatures(functions=["mean", "skew", "sem"]).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..fa5dbfab4 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,31 @@ 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_mean", "a_sum"] + Xt = add_expanding_window_features( + X, ["a"], ["max", "mean", "sum"], None, 1, None, False, 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_mean": [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]})), ["sem"], ["mean"]) + + msg = ( + "With dataframes other than pandas, functions takes only ['max', 'mean']. " + "Got sem instead." + ) + with pytest.raises(NotImplementedError, match=re.escape(msg)): + check_functions_supported( + check_X(pl.DataFrame({"a": [1]})), "sem", ["mean", "max"] + ) From e429e282aecc83872da53ee6bb81a36ecf267e1c Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Thu, 26 Nov 2026 16:17:28 +0100 Subject: [PATCH 3/3] apply the WindowFeatures review to ExpandingWindowFeatures With polars, ExpandingWindowFeatures now takes the 15 pandas expanding functions that aggregate one variable: first, last, nunique and sem with narwhals, and skew, kurt and rank with polars, as median. __init__ validates min_periods and sort_index, rejects periods=True, and its messages end with "Got ... instead.". The helpers have no early returns, and the functions check is shared with WindowFeatures. The tests check the column order and drop_original with drop_na on both libraries, and the user guide shows the feature names before the polars section, which redefined X. Co-Authored-By: Claude Opus 5.5 --- .../forecasting/ExpandingWindowFeatures.rst | 86 ++++--- .../forecasting/_forecasting_helpers.py | 146 ++++++------ .../forecasting/expanding_window_features.py | 66 +++--- .../test_expanding_window_features.py | 209 +++++++++++------- .../test_forecasting_helpers.py | 19 +- 5 files changed, 304 insertions(+), 222 deletions(-) diff --git a/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst b/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst index 2084f073c..2842b1769 100644 --- a/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst +++ b/docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst @@ -64,13 +64,16 @@ the same type of dataframe it receives. 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 operation -supported by pandas. For supported aggregation functions, see Expanding Window +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 polars dataframes, :class:`ExpandingWindowFeatures` supports the functions `"count"`, -`"sum"`, `"mean"`, `"median"`, `"min"`, `"max"`, `"std"` and `"var"`, and returns the -same values as pandas. +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 @@ -431,6 +434,32 @@ The original variable is no longer in the output dataframe: 2020-05-15 12:45:00 31.656667 32.15 2020-05-15 13:00:00 31.840000 32.39 +Getting the name of the new features +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We can easily obtain the name of the original and new variables with the method +`get_feature_names_out`. + +.. code:: python + + win_f = ExpandingWindowFeatures() + + win_f.fit(X) + + win_f.get_feature_names_out() + +We obtain the names of the original variables plus the new expanding window features: + +.. code:: python + + ['ambient_temp', + 'module_temp', + 'irradiation', + 'color', + 'ambient_temp_expanding_mean', + 'module_temp_expanding_mean', + 'irradiation_expanding_mean'] + With polars ~~~~~~~~~~~ @@ -482,41 +511,34 @@ so its expanding window features are null: │ 2020-05-15 13:00 ┆ 32.62 ┆ 31.84 ┆ 32.39 │ └──────────────────┴──────────────┴─────────────────────────────┴────────────────────────────┘ -With polars, other functions, like `"skew"`, raise an error: - -.. code:: python - - ExpandingWindowFeatures(functions=["skew"]).fit_transform(X) - -.. code:: text - - NotImplementedError: With dataframes other than pandas, functions takes only ['count', 'max', 'mean', 'median', 'min', 'std', 'sum', 'var']. Got ['skew'] instead. - -Getting the name of the new features -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -We can easily obtain the name of the original and new variables with the method -`get_feature_names_out`. +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() + win_f = ExpandingWindowFeatures(functions=["rank", "sem"]) - win_f.fit(X) + X_tr = win_f.fit_transform(X) - win_f.get_feature_names_out() + print(X_tr) -We obtain the names of the original variables plus the new expanding window features: +The temperature rises over time, so each past value is the highest so far, and its rank +is the number of past values: -.. code:: python +.. code:: text - ['ambient_temp', - 'module_temp', - 'irradiation', - 'color', - 'ambient_temp_expanding_mean', - 'module_temp_expanding_mean', - 'irradiation_expanding_mean'] + 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 a287b4dff..c20fd5476 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -199,7 +199,7 @@ def add_lag_features( def check_functions_supported( - X: DataFrame, functions: Union[str, List[str]], supported: List[str] + X: DataFrame, functions: Union[str, List[str]] ) -> None: """ Checks that dataframes other than pandas use functions that they support. @@ -211,20 +211,16 @@ def check_functions_supported( functions : str or list The `functions` parameter of the transformer. - - supported : list - The functions supported with dataframes other than pandas. """ # pandas supports every function. - if not isinstance(X, nw.DataFrame): - return - - function_list = functions if isinstance(functions, list) else [functions] - if not all(function in supported for function in function_list): - raise NotImplementedError( - "With dataframes other than pandas, functions takes only " - f"{sorted(supported)}. Got {functions} instead." - ) + 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( @@ -261,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 " @@ -427,54 +417,72 @@ def add_expanding_window_features( .shift(periods=periods, freq=freq) ) tmp.columns = names - return X.merge(tmp, left_index=True, right_index=True, how="left") - - # pandas treats min_periods=None as 0. narwhals' rolling functions need at - # least 1, and 0 only changes the 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() - 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 in ("min", "max"): - # cumulative min and max are faster than rolling ones, but - # they are null in the rows with missing data. - cum = x.cum_min() if func == "min" else x.cum_max() - feature = nw.when(count >= min_samples).then( - cum.fill_null(strategy="forward") - ) - elif func == "median": - # narwhals has no rolling median: use the polars series. - values = X.select(x).get_column(var).to_native() - feature = nw.from_native( - values.rolling_median(window, min_samples=min_samples), - series_only=True, - ) + 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: - feature = getattr(x, f"rolling_{func}")( - window, min_samples=min_samples - ) - if func == "sum" and min_periods == 0: - feature = feature.fill_null(0) - new_features.append(feature.shift(periods)) + 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.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 3aa67e390..46aa1bfc6 100644 --- a/feature_engine/timeseries/forecasting/expanding_window_features.py +++ b/feature_engine/timeseries/forecasting/expanding_window_features.py @@ -37,9 +37,6 @@ BaseForecastTransformer, ) -# functions supported with dataframes other than pandas. -_FUNCTIONS = ["count", "sum", "mean", "median", "min", "max", "std", "var"] - @Substitution( variables=_variables_numerical_docstring, @@ -74,10 +71,8 @@ class ExpandingWindowFeatures(BaseForecastTransformer): The dataframe's index orders the rows in time, so it must have unique values and no NaN. - With polars, ExpandingWindowFeatures supports the functions 'count', 'sum', - 'mean', 'median', 'min', 'max', 'std' and 'var', and returns the same values - as pandas. 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. + 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, @@ -98,10 +93,15 @@ class ExpandingWindowFeatures(BaseForecastTransformer): `expanding()` documentation for more details. functions: str, list of str, default = 'mean' - The functions to apply within the window. With pandas, valid functions can be - found `here `_. With - polars, the functions can be 'count', 'sum', 'mean', 'median', 'min', 'max', - 'std' and 'var'. + 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 @@ -215,23 +215,41 @@ def __init__( drop_na: bool = False, ) -> None: + 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( - "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 ) @@ -255,7 +273,7 @@ def fit(self, X: IntoDataFrame, y: IntoSeries | None = 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, _FUNCTIONS) + check_functions_supported(check_X(X), self.functions) return self def transform(self, X: IntoDataFrame) -> IntoDataFrame: @@ -296,19 +314,13 @@ def transform(self, X: IntoDataFrame) -> IntoDataFrame: return nw.to_native(X, pass_through=True) - def _functions_list(self) -> List[str]: - """Return the functions as a list.""" - if isinstance(self.functions, list): - return self.functions - return [self.functions] - def _get_new_features_name(self) -> List: - """Get names of the window features.""" - - 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 self._functions_list() + 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 c72f5ad0d..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 @@ -16,39 +16,64 @@ DATES = pd.date_range("2020-05-15 12:00:00", periods=6, freq="15min") +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"] + # 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) + + @pytest.mark.parametrize( "functions", [[np.min, np.max], np.min, 1, None, [], "", ["mean", 1], ("mean",)] ) def test_error_if_functions_not_permitted(functions): - msg = f"functions must be a list of strings or a string. Got {functions} instead." + 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) -def test_error_if_functions_duplicated(): - msg = "There are duplicated functions in the list: ['sum', 'mean', 'sum']" +@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=["sum", "mean", "sum"]) + ExpandingWindowFeatures(functions=functions) -@pytest.mark.parametrize("periods", [-1, 1.5, "1", None, [1]]) +@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), - (1, ["max"], 2, "1h", True, "raise", False, True), + (0, ["max"], 2, "1h", True, "raise", False, True), ], ) def test_init_param_assignment( @@ -104,19 +129,15 @@ def test_init_param_assignment( ], ) def test_get_feature_names_out(make_df, variables, functions, expected): + X = make_df(DATA) transformer = ExpandingWindowFeatures(variables=variables, functions=functions) - transformer.fit(make_df(DATA)) + transformer.fit(X) + original = ["x1", "x2", "color"] - assert transformer.get_feature_names_out() == ["x1", "x2", "color"] + expected - assert ( - transformer.get_feature_names_out(["x1", "x2", "color"]) - == [ - "x1", - "x2", - "color", - ] - + expected - ) + 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): @@ -149,36 +170,38 @@ def test_default_expanding_mean_of_all_numerical_variables(make_df): } -def test_all_functions_supported_with_polars(make_df): - functions = ["count", "sum", "mean", "median", "min", "max", "std", "var"] +@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) - Xt = ExpandingWindowFeatures(variables="x2", functions=functions).fit_transform(X) + transformer = ExpandingWindowFeatures(variables="x2", functions=function) + Xt = transformer.fit_transform(X) assert isinstance(Xt, make_df) - assert frame_to_dict(Xt) == { - **DATA, - "x2_expanding_count": [None, 1.0, 2.0, 3.0, 4.0, 5.0], - "x2_expanding_sum": [None, 2.0, 9.0, 10.0, 18.0, 20.0], - "x2_expanding_mean": pytest.approx( - [None, 2.0, 4.5, 3.3333333333333335, 4.5, 4.0] - ), - "x2_expanding_median": [None, 2.0, 4.5, 2.0, 4.5, 2.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], - "x2_expanding_std": pytest.approx( - [ - None, - None, - 3.5355339059327378, - 3.214550253664318, - 3.5118845842842465, - 3.24037034920393, - ] - ), - "x2_expanding_var": pytest.approx( - [None, None, 12.5, 10.333333333333332, 12.333333333333334, 10.5] - ), - } + # the first row has no past values + assert frame_to_dict(Xt)[f"x2_expanding_{function}"] == pytest.approx( + [None] + expected, abs=1e-6 + ) @pytest.mark.parametrize( @@ -246,6 +269,39 @@ def test_min_periods_and_missing_data(make_df, min_periods, expected): 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( + functions=function, min_periods=min_periods, missing_values="ignore" + ) + 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]}) @@ -269,6 +325,8 @@ def test_drop_original(make_df): 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], @@ -297,6 +355,21 @@ def test_drop_na(make_df): } +def test_drop_original_and_drop_na(make_df): + X = make_df(DATA) + transformer = ExpandingWindowFeatures( + functions="std", drop_original=True, drop_na=True + ) + 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]), + } + + @pytest.mark.parametrize( "drop_na, expected", [(True, [3, 4, 5, 6]), (False, [1, 2, 3, 4, 5, 6])] ) @@ -364,32 +437,6 @@ def test_sort_index_with_pandas(): pd.testing.assert_frame_equal(Xt, expected) -def test_functions_not_supported_by_polars_with_pandas(): - X = pd.DataFrame(DATA) - transformer = ExpandingWindowFeatures(variables="x2", functions=["skew", "sem"]) - Xt = transformer.fit_transform(X) - - expected = X.assign( - x2_expanding_skew=[ - np.nan, - np.nan, - np.nan, - 1.545392525695021, - 0.0, - 0.5878222855698739, - ], - x2_expanding_sem=[ - np.nan, - np.nan, - 2.5, - 1.855921454276674, - 1.7559422921421233, - 1.4491376746189437, - ], - ) - 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( @@ -412,21 +459,13 @@ def test_integer_column_names_with_pandas(): pd.testing.assert_frame_equal(Xt, expected) -# polars: the rows are used in the order given -def test_rows_are_used_in_the_order_given_with_polars(): - X = pl.DataFrame({"x": [8.0, 2.0, 7.0, 1.0]}) - Xt = ExpandingWindowFeatures(functions="min", sort_index=True).fit_transform(X) - - assert frame_to_dict(Xt)["x_expanding_min"] == [None, 8.0, 2.0, 2.0] - - -def test_error_if_function_not_supported_with_polars(): +# 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', 'max', 'mean', 'median', 'min', 'std', 'sum', 'var']. " - "Got ['mean', 'skew', 'sem'] instead." + "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." ) with pytest.raises(NotImplementedError, match=re.escape(msg)): - ExpandingWindowFeatures(functions=["mean", "skew", "sem"]).fit( - pl.DataFrame(DATA) - ) + 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 fa5dbfab4..86eba078a 100644 --- a/tests/test_time_series/test_forecasting/test_forecasting_helpers.py +++ b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py @@ -142,27 +142,28 @@ def test_check_window_parameters_accepts_everything_with_pandas( 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_mean", "a_sum"] + names = ["a_max", "a_median", "a_sum"] Xt = add_expanding_window_features( - X, ["a"], ["max", "mean", "sum"], None, 1, None, False, names + 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_mean": [None, 1.0, 2.0, 2.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]})), ["sem"], ["mean"]) + check_functions_supported(check_X(pd.DataFrame({"a": [1]})), ["quantile"]) msg = ( - "With dataframes other than pandas, functions takes only ['max', 'mean']. " - "Got sem instead." + "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]})), "sem", ["mean", "max"] - ) + check_functions_supported(check_X(pl.DataFrame({"a": [1]})), "quantile")