From 7360617d90a0bcd7fcc54280e67a01d84027f6e4 Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Sat, 19 Sep 2026 12:06:06 +0200 Subject: [PATCH 1/7] Migrate WindowFeatures to narwhals, add polars support WindowFeatures takes pandas and polars dataframes. With pandas it keeps rolling on the index, including time-span windows, freq and all rolling functions; it now calls the rolling methods instead of agg(), which is faster with many variables. With polars the rows are used in the order given, windows are numbers of rows, and mean, sum, std, var and count use narwhals, while min, max, median, skew and kurt use polars expressions. Time-span windows, other functions and min_periods=0 raise a clear error with polars. Also stops return_empty=True from failing with lists of windows or functions when there are no numerical variables. Co-Authored-By: Claude Opus 5 --- .../timeseries/forecasting/WindowFeatures.rst | 101 +- .../timeseries/forecasting/window_features.py | 233 ++++- .../test_forecasting/test_window_features.py | 882 +++++++----------- 3 files changed, 621 insertions(+), 595 deletions(-) diff --git a/docs/user_guide/timeseries/forecasting/WindowFeatures.rst b/docs/user_guide/timeseries/forecasting/WindowFeatures.rst index f601afcb6..ddec26a5d 100644 --- a/docs/user_guide/timeseries/forecasting/WindowFeatures.rst +++ b/docs/user_guide/timeseries/forecasting/WindowFeatures.rst @@ -33,7 +33,7 @@ by executing: .. code:: python - X[["var_1", "var_2"].rolling(window=3).agg(["max", "mean"]) + X[["var_1", "var_2"]].rolling(window=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 the current and 2 previous rows of data. @@ -43,7 +43,7 @@ algorithms, we also need to shift the window forward with pandas method `shift`: .. code:: python - X[["var_1", "var_2"].rolling(window=3).agg(["max", "mean"]).shift(period=1) + X[["var_1", "var_2"]].rolling(window=3).agg(["max", "mean"]).shift(periods=1) Shifting is important to ensure that we are using values strictly in the past, with respect to the point that we want to forecast. @@ -72,15 +72,15 @@ weeks data, leaving a gap of a window in between the window feature and the fore WindowFeatures: under the hood ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:class:`WindowFeatures` works on top of `pandas.rolling`, `pandas.aggregate` and +With pandas, :class:`WindowFeatures` works on top of `pandas.rolling` and `pandas.shift`. With `pandas.rolling`, :class:`WindowFeatures` determines the size of the windows for the operations. With `pandas.rolling` we can specify the window size with an integer, a string or a function. With :class:`WindowFeatures`, in addition, we can pass a list of integers, strings or functions, to perform computations over multiple window sizes. -:class:`WindowFeatures` uses `pandas.aggregate` to perform the mathematical operations -over the windows. Therefore, you can use any operation supported +:class:`WindowFeatures` performs the mathematical operations over the windows with the +methods of `pandas.rolling`. Therefore, you can use any operation supported by pandas. For supported aggregation functions, see Rolling Window `Functions `_. @@ -94,8 +94,10 @@ forward the value 2 weeks forward. 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:`WindowFeatures` only works with dataframes whose index, -containing the time series timestamp, contains unique values and no NaN. +:class:`WindowFeatures` works with pandas and polars dataframes. With pandas, the rows are +ordered in time by the dataframe's index, which should contain the time series timestamp, +with unique values and no NaN. Polars dataframes have no index, so the rows are used in the +order given. See :ref:`Window features with polars ` below. .. attention:: @@ -504,7 +506,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:`WindowFeatures` to create, for example, 2 new window features by finding the mean and maximum value within a 45 minute windows of a pandas Series if we convert it @@ -604,6 +606,89 @@ We obtain the names of the original variables plus the new window features: 'module_temp_window_3_mean', 'irradiation_window_3_mean'] +.. _window_features_polars: + +Window features with polars +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:class:`WindowFeatures` also creates window features from polars dataframes. Polars +dataframes have no index, so the rows are used in the order given: make sure they are +sorted in time before creating the features. For the same reason, with polars: + +- `window` takes the number of rows in each window, as an integer or a list of integers. + Time spans, like `"30min"`, are not supported. +- `freq` is not supported: the window features are shifted by `periods` rows. +- `functions` takes `"count"`, `"kurt"`, `"max"`, `"mean"`, `"median"`, `"min"`, + `"skew"`, `"std"`, `"sum"` and `"var"`. +- `min_periods` must be greater than 0. +- `sort_index` does not apply. + +Let's create a polars dataframe with the ambient temperature and irradiation of our +previous example, which were recorded every 15 minutes: + +.. code:: python + + import polars as pl + from feature_engine.timeseries.forecasting import WindowFeatures + + X = pl.DataFrame({ + "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68], + "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42, 0.49, 0.57, 0.56], + }) + +Windows of 2 and 4 rows cover 30 and 60 minutes of data: + +.. code:: python + + win_f = WindowFeatures(window=[2, 4], functions="mean") + + X_tr = win_f.fit_transform(X) + + print(X_tr) + +We see the window features on the right of the dataframe. The first rows, which don't +have enough past data to fill the window, contain null values: + +.. code:: python + + shape: (8, 6) + ┌──────────────┬─────────────┬─────────────────┬─────────────────┬────────────────┬────────────────┐ + │ ambient_temp ┆ irradiation ┆ ambient_temp_wi ┆ irradiation_win ┆ ambient_temp_w ┆ irradiation_wi │ + │ --- ┆ --- ┆ ndow_2_mean ┆ dow_2_mean ┆ indow_4_mean ┆ ndow_4_mean │ + │ f64 ┆ f64 ┆ --- ┆ --- ┆ --- ┆ --- │ + │ ┆ ┆ f64 ┆ f64 ┆ f64 ┆ f64 │ + ╞══════════════╪═════════════╪═════════════════╪═════════════════╪════════════════╪════════════════╡ + │ 31.31 ┆ 0.51 ┆ null ┆ null ┆ null ┆ null │ + │ 31.51 ┆ 0.79 ┆ null ┆ null ┆ null ┆ null │ + │ 32.15 ┆ 0.65 ┆ 31.41 ┆ 0.65 ┆ null ┆ null │ + │ 32.39 ┆ 0.76 ┆ 31.83 ┆ 0.72 ┆ null ┆ null │ + │ 32.62 ┆ 0.42 ┆ 32.27 ┆ 0.705 ┆ 31.84 ┆ 0.6775 │ + │ 32.5 ┆ 0.49 ┆ 32.505 ┆ 0.59 ┆ 32.1675 ┆ 0.655 │ + │ 32.52 ┆ 0.57 ┆ 32.56 ┆ 0.455 ┆ 32.415 ┆ 0.58 │ + │ 32.68 ┆ 0.56 ┆ 32.51 ┆ 0.53 ┆ 32.5075 ┆ 0.56 │ + └──────────────┴─────────────┴─────────────────┴─────────────────┴────────────────┴────────────────┘ + +To take windows with fewer rows at the start of the series, set `min_periods`. + +We can also drop the rows with null values in the window features from the dataframe and +the target: + +.. code:: python + + y = pl.Series("y", [1, 2, 3, 4, 5, 6, 7, 8]) + + win_f = WindowFeatures(window=[2, 4], functions=["mean", "max"], drop_na=True) + + X_tr, y_tr = win_f.fit(X).transform_x_y(X, y) + + print(X.shape, y.shape, X_tr.shape, y_tr.shape) + +The first 4 rows were removed from both: + +.. code:: python + + (8, 2) (8,) (4, 10) (4,) + Windows from the target vs windows from predictor variables ----------------------------------------------------------- diff --git a/feature_engine/timeseries/forecasting/window_features.py b/feature_engine/timeseries/forecasting/window_features.py index f5f73c7f7..3fb9733b6 100644 --- a/feature_engine/timeseries/forecasting/window_features.py +++ b/feature_engine/timeseries/forecasting/window_features.py @@ -1,6 +1,9 @@ +from itertools import product from typing import Callable, List, Union -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, @@ -21,6 +24,34 @@ BaseForecastTransformer, ) +# pandas' rolling functions that other dataframes support: with narwhals, or with +# polars' own expressions when narwhals has none (they are faster than numpy). +_NW_ROLLING = { + "count": lambda col, win, min_samples: (~col.is_null()) + .cast(nw.Float64) + .rolling_sum(win, min_samples=min_samples), + "mean": lambda col, win, min_samples: col.rolling_mean( + win, min_samples=min_samples + ), + "std": lambda col, win, min_samples: col.rolling_std(win, min_samples=min_samples), + "sum": lambda col, win, min_samples: col.rolling_sum(win, min_samples=min_samples), + "var": lambda col, win, min_samples: col.rolling_var(win, min_samples=min_samples), +} +_POLARS_ROLLING = { + # bias=False gives the sample skewness and kurtosis, as pandas. + "kurt": lambda col, win, min_samples: col.rolling_kurtosis( + win, bias=False, min_samples=min_samples + ), + "max": lambda col, win, min_samples: col.rolling_max(win, min_samples=min_samples), + "median": lambda col, win, min_samples: col.rolling_median( + win, min_samples=min_samples + ), + "min": lambda col, win, min_samples: col.rolling_min(win, min_samples=min_samples), + "skew": lambda col, win, min_samples: col.rolling_skew( + win, bias=False, min_samples=min_samples + ), +} + @Substitution( variables=_variables_numerical_docstring, @@ -41,11 +72,12 @@ class WindowFeatures(BaseForecastTransformer): example, the mean value of the previous 3 months of data is a window feature. The maximum value of the previous three rows of data is another window feature. - WindowFeatures uses pandas functions `rolling()`, `agg()` and `shift()`. With - `rolling()`, it creates rolling windows. With `agg()` it applies multiple functions - within those windows. With `shift()` it allocates the values to the correct rows. + WindowFeatures works with pandas and polars dataframes. - For supported aggregation functions, see Rolling Window + With pandas, WindowFeatures uses pandas functions `rolling()` and `shift()`. With + `rolling()`, it creates rolling windows and applies the functions within those + windows. With `shift()` it allocates the values to the correct rows. For supported + aggregation functions, see Rolling Window `Functions `_. With pandas `rolling()` we can perform rolling operations over 1 window size at a @@ -53,8 +85,10 @@ class WindowFeatures(BaseForecastTransformer): be derived from multiple window sizes, and the created features will be automatically concatenated to the original dataframe. - To be compatible with WindowFeatures, the dataframe's index must have unique values - and no missing data. + With pandas, the rows are ordered in time by the dataframe's index, which must have + unique values and no missing data. Polars dataframes have no index: their rows are + taken in the order given, so they must be sorted in time. With polars, the windows + are a number of rows, and `freq` is not supported. WindowFeatures works only with numerical variables. You can pass a list of variables to use as input for the windows. Alternatively, WindowFeatures will automatically @@ -78,25 +112,31 @@ class WindowFeatures(BaseForecastTransformer): the above specified values, in which case, features will be created for each one of the windows specified in the list. + With polars, `window` takes only integers or lists of integers. + min_periods: int, default None. Minimum number of observations in the window required to have a value; otherwise, the result is np.nan. See parameter `min_periods` in pandas - `rolling()` documentation for more details. + `rolling()` documentation for more details. With polars, `min_periods` must be + greater than 0. functions: string or list of strings, default = 'mean' The functions to apply within the window. Valid functions can be found - `here `_. + `here `_. With polars, + the valid functions are 'count', 'kurt', 'max', 'mean', 'median', 'min', + 'skew', 'std', 'sum' and 'var'. - periods: int, list of ints, default=1 + periods: int, 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 + 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. sort_index: bool, default=True - Whether to order the index of the dataframe before creating the features. + Whether to order the index of the dataframe before creating the features. It + does not apply to polars dataframes, which have no index. {missing_values} @@ -153,6 +193,25 @@ class WindowFeatures(BaseForecastTransformer): 2 2022-09-20 3 8 1.5 6.5 3 2022-09-21 4 9 2.5 7.5 4 2022-09-22 5 10 3.5 8.5 + + With polars, the rows are taken in the order given: + + >>> import polars as pl + >>> X = pl.DataFrame(dict(x1 = [1,2,3,4,5], x2 = [6,7,8,9,10])) + >>> wf = WindowFeatures(window = 2) + >>> wf.fit_transform(X) + shape: (5, 4) + ┌─────┬─────┬──────────────────┬──────────────────┐ + │ x1 ┆ x2 ┆ x1_window_2_mean ┆ x2_window_2_mean │ + │ --- ┆ --- ┆ --- ┆ --- │ + │ i64 ┆ i64 ┆ f64 ┆ f64 │ + ╞═════╪═════╪══════════════════╪══════════════════╡ + │ 1 ┆ 6 ┆ null ┆ null │ + │ 2 ┆ 7 ┆ null ┆ null │ + │ 3 ┆ 8 ┆ 1.5 ┆ 6.5 │ + │ 4 ┆ 9 ┆ 2.5 ┆ 7.5 │ + │ 5 ┆ 10 ┆ 3.5 ┆ 8.5 │ + └─────┴─────┴──────────────────┴──────────────────┘ """ def __init__( @@ -199,54 +258,134 @@ def __init__( self.freq = freq self.sort_index = sort_index - def transform(self, X: pd.DataFrame) -> pd.DataFrame: + def _check_index(self, X: IntoDataFrame): + """ + Checks that the rows of the dataframe can be ordered in time and, with + dataframes other than pandas, that `window`, `functions` and `min_periods` + are supported. + + Parameters + ---------- + X: dataframe of shape = [n_samples, n_features] + The dataset. + """ + super()._check_index(X) + + if nwd.is_pandas_dataframe(X) is False: + windows = self.window if isinstance(self.window, list) else [self.window] + if not all(isinstance(win, int) for win in windows): + raise NotImplementedError( + "Time spans in window, like '3D', are only supported with pandas " + "dataframes, because they use the dataframe's DatetimeIndex. With " + "other dataframes, window takes integers, the number of rows in " + f"each window. Got {self.window} instead." + ) + + functions = ( + self.functions if isinstance(self.functions, list) else [self.functions] + ) + if not all( + function in _NW_ROLLING or function in _POLARS_ROLLING + for function in functions + ): + raise NotImplementedError( + "With dataframes other than pandas, functions takes only " + f"{sorted([*_NW_ROLLING, *_POLARS_ROLLING])}. " + f"Got {self.functions} instead." + ) + + if self.min_periods == 0: + raise NotImplementedError( + "min_periods=0 is only supported with pandas dataframes. With " + "other dataframes, min_periods takes integers greater than 0 or " + f"None. Got {self.min_periods} instead." + ) + + return self + + def transform(self, X: IntoDataFrame) -> IntoDataFrame: """ Adds 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) - - if isinstance(self.window, list): - df_ls = [] - for win in self.window: - tmp = ( - X[self.variables_] - .rolling(window=win, min_periods=self.min_periods) - .agg(self.functions) - .shift(periods=self.periods, freq=self.freq) - ) - df_ls.append(tmp) - tmp = pd.concat(df_ls, axis=1, sort=False) - - else: - tmp = ( - X[self.variables_] - .rolling(window=self.window, min_periods=self.min_periods) - .agg(self.functions) - .shift(periods=self.periods, freq=self.freq) - ) - - tmp.columns = self._get_new_features_name() + return super().transform(X) - X = X.merge(tmp, left_index=True, right_index=True, how="left") + def _add_features(self, nw_X: nw.DataFrame) -> nw.DataFrame: + """ + Adds the window features after the columns of `nw_X`. - if self.drop_original: - X = X.drop(self.variables_, axis=1) + Parameters + ---------- + nw_X: narwhals dataframe of shape = [n_samples, n_features] + The data returned by `_check_transform_input_and_state()`. + """ + if len(self.variables_) == 0: + return nw_X - if self.drop_na: - X = X.dropna(subset=tmp.columns, axis=0) + windows = self.window if isinstance(self.window, list) else [self.window] + functions = ( + self.functions if isinstance(self.functions, list) else [self.functions] + ) + new_features = self._get_new_features_name() + X = nw_X.to_native() + + if nwd.is_pandas_dataframe(X) is True: + # pandas is faster than narwhals, and time spans and freq need its index. + tmp = [] + for win in windows: + rolling = X[self.variables_].rolling( + window=win, min_periods=self.min_periods + ) + for function in functions: + # the rolling methods are faster than agg() with many variables. + rolled = getattr(rolling, function)().shift( + periods=self.periods, freq=self.freq + ) + rolled.columns = [ + f"{var}_window_{win}_{function}" for var in self.variables_ + ] + tmp.append(rolled) + # with freq, the index of the features moves: merge aligns them to X. + X = X.merge( + tmp[0].join(tmp[1:])[new_features], + left_index=True, + right_index=True, + how="left", + ) + return nw.from_native(X, eager_only=True) - return X + plx = nw.get_native_namespace(nw_X) + nw_exprs, native_exprs = [], [] + for name, (win, var, function) in zip( + new_features, product(windows, self.variables_, functions) + ): + # like pandas, windows of integers need all their rows by default. + min_samples = win if self.min_periods is None else self.min_periods + if function in _NW_ROLLING: + rolled = _NW_ROLLING[function](nw.col(var), win, min_samples) + nw_exprs.append(rolled.shift(self.periods).alias(name)) + else: + rolled = _POLARS_ROLLING[function](plx.col(var), win, min_samples) + native_exprs.append(rolled.shift(self.periods).alias(name)) + + columns = nw_X.columns + nw_X = nw_X.with_columns(nw_exprs) + if len(native_exprs) > 0: + # the polars features were added last: restore the order of the names. + X = nw_X.to_native().with_columns(native_exprs) + nw_X = nw.from_native(X, eager_only=True).select(columns + new_features) + + return nw_X def _get_new_features_name(self) -> List: """Get names of the lag features.""" diff --git a/tests/test_time_series/test_forecasting/test_window_features.py b/tests/test_time_series/test_forecasting/test_window_features.py index 1ec83ed8e..6c475e305 100644 --- a/tests/test_time_series/test_forecasting/test_window_features.py +++ b/tests/test_time_series/test_forecasting/test_window_features.py @@ -1,634 +1,436 @@ +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 WindowFeatures +from tests.backend_helpers import frame_to_dict, make_series -_date_time = [ - pd.Timestamp("2020-05-15 12:00:00"), - pd.Timestamp("2020-05-15 12:15:00"), - pd.Timestamp("2020-05-15 12:30:00"), - pd.Timestamp("2020-05-15 12:45:00"), - pd.Timestamp("2020-05-15 13:00:00"), - pd.Timestamp("2020-05-15 13:15:00"), - pd.Timestamp("2020-05-15 13:30:00"), - pd.Timestamp("2020-05-15 13:45:00"), - pd.Timestamp("2020-05-15 14:00:00"), -] +DATA = { + "x1": [1.0, 2.0, 4.0, 7.0, 11.0, 16.0, 22.0], + "x2": [10, 20, 30, 40, 50, 60, 70], + "cat": ["a", "b", "c", "d", "e", "f", "g"], +} +MSG_POLARS_FUNCTIONS = ( + "With dataframes other than pandas, functions takes only ['count', 'kurt', " + "'max', 'mean', 'median', 'min', 'skew', 'std', 'sum', 'var']. " +) -@pytest.mark.parametrize("_window", [[2, 2, 3], ["45min", "45min", "30min"]]) -def test_error_when_duplicated_windows(_window): - with pytest.raises(ValueError): - WindowFeatures(window=_window) +# init parameters +@pytest.mark.parametrize("window", [[2, 2, 3], ["45min", "45min", "30min"]]) +def test_error_if_window_duplicated(window): + msg = f"There are duplicated windows in the list: {window}" + with pytest.raises(ValueError, match=re.escape(msg)): + WindowFeatures(window=window) -@pytest.mark.parametrize("_periods", [1, 2, 3]) -def test_permitted_param_periods(_periods): - transformer = WindowFeatures(periods=_periods) - assert transformer.periods == _periods +@pytest.mark.parametrize("functions", [3.33, [1, "mean"], None, ("mean", "sum")]) +def test_error_if_functions_not_string_or_list(functions): + msg = f"functions must be a string or a list of strings. Got {functions} instead." + with pytest.raises(ValueError, match=re.escape(msg)): + WindowFeatures(functions=functions) -@pytest.mark.parametrize("_periods", ["pizza", 3.33, ["mate", "cumbia"], None]) -def test_error_when_non_permitted_param_periods(_periods): - with pytest.raises(ValueError): - WindowFeatures(periods=_periods) +def test_error_if_functions_duplicated(): + msg = "There are duplicated functions in the list: ['sum', 'sum', 'mean']" + with pytest.raises(ValueError, match=re.escape(msg)): + WindowFeatures(functions=["sum", "sum", "mean"]) -@pytest.mark.parametrize( - "_functions", ["mean", "std", ["sum", "mean"], ["sum", "mean", "count"]] -) -def test_permitted_param_functions(_functions): - transformer = WindowFeatures(functions=_functions) - assert transformer.functions == _functions + +@pytest.mark.parametrize("periods", ["pizza", 3.33, ["mate", "cumbia"], None, 0, -1]) +def test_error_if_periods_not_positive_integer(periods): + msg = f"periods must be a positive integer. Got {periods} instead." + with pytest.raises(ValueError, match=re.escape(msg)): + WindowFeatures(periods=periods) @pytest.mark.parametrize( - "_functions", [3.33, [1, "mean"], None, ["sum", "sum", "mean"]] + "window, min_periods, functions, periods, freq, sort_index", + [ + (3, None, "mean", 1, None, True), + ([2, 3], 1, ["sum", "mean", "count"], 2, "15min", False), + (["45min", "30min"], 2, ["std"], 3, "1h", True), + ], ) -def test_error_when_non_permitted_param_functions(_functions): - with pytest.raises(ValueError): - WindowFeatures(functions=_functions) - - -@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): - WindowFeatures(drop_original=_drop_or) +def test_init_param_assignment( + window, min_periods, functions, periods, freq, sort_index +): + transformer = WindowFeatures( + window=window, + min_periods=min_periods, + functions=functions, + periods=periods, + freq=freq, + sort_index=sort_index, + missing_values="ignore", + drop_original=True, + drop_na=True, + ) + assert transformer.window == window + 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 == "ignore" + assert transformer.drop_original is True + assert transformer.drop_na is True + + +# fit and transform +def test_get_feature_names_out(make_df): + X = make_df(DATA) + original = ["x1", "x2", "cat"] + + transformer = WindowFeatures(window=3, functions=["mean", "sum"]).fit(X) + expected = original + [ + "x1_window_3_mean", + "x1_window_3_sum", + "x2_window_3_mean", + "x2_window_3_sum", + ] + assert transformer.get_feature_names_out() == expected + assert transformer.get_feature_names_out(input_features=original) == expected + + transformer = WindowFeatures(window=[2, 3], functions="mean").fit(X) + assert transformer.get_feature_names_out() == original + [ + "x1_window_2_mean", + "x2_window_2_mean", + "x1_window_3_mean", + "x2_window_3_mean", + ] + transformer = WindowFeatures(variables="x2", drop_original=True).fit(X) + assert transformer.get_feature_names_out() == ["x1", "cat", "x2_window_3_mean"] + + +@pytest.mark.parametrize("input_features", [["x1"], ["cat"]]) +def test_error_if_input_features_differ_from_fit(make_df, input_features): + transformer = WindowFeatures().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=input_features) + + +def test_error_if_input_features_not_list(make_df): + transformer = WindowFeatures().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_multiple_windows_and_functions(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=[2, 3], functions=["sum", "mean"]).fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "x1_window_2_sum": [None, None, 3.0, 6.0, 11.0, 18.0, 27.0], + "x1_window_2_mean": [None, None, 1.5, 3.0, 5.5, 9.0, 13.5], + "x2_window_2_sum": [None, None, 30, 50, 70, 90, 110], + "x2_window_2_mean": [None, None, 15.0, 25.0, 35.0, 45.0, 55.0], + "x1_window_3_sum": [None, None, None, 7.0, 13.0, 22.0, 34.0], + "x1_window_3_mean": pytest.approx( + [None, None, None, 7 / 3, 13 / 3, 22 / 3, 34 / 3] + ), + "x2_window_3_sum": [None, None, None, 60, 90, 120, 150], + "x2_window_3_mean": [None, None, None, 20.0, 30.0, 40.0, 50.0], + } -@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): - WindowFeatures(drop_na=_drop_na) +@pytest.mark.parametrize( + "function, expected", + [ + ("count", [4.0, 4.0, 4.0]), + ("sum", [14.0, 24.0, 38.0]), + ("mean", [3.5, 6.0, 9.5]), + ("median", [3.0, 5.5, 9.0]), + ("var", [7.0, 15.333333, 27.0]), + ("std", [2.645751, 3.915780, 5.196152]), + ("min", [1.0, 2.0, 4.0]), + ("max", [7.0, 11.0, 16.0]), + ("skew", [0.863919, 0.599581, 0.456178]), + ("kurt", [-0.285714, -0.768431, -0.951989]), + ], +) +def test_functions(make_df, function, expected): + X = make_df(DATA) + Xt = WindowFeatures(variables="x1", window=4, functions=function).fit_transform(X) + + assert isinstance(Xt, make_df) + # the first window with 4 rows is shifted to the fifth row + assert frame_to_dict(Xt)[f"x1_window_4_{function}"] == pytest.approx( + [None, None, None, None] + expected, abs=1e-6 + ) -def test_get_feature_names_out(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] - # case 1: 1 window, multiple variables, multiple functions - tr = WindowFeatures(window=3, functions=["mean", "sum"]) - tr.fit(df_time) +def test_periods(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=2, functions="max", periods=3).fit_transform(X) - # expected - output = [ - "ambient_temp_window_3_mean", - "ambient_temp_window_3_sum", - "module_temp_window_3_mean", - "module_temp_window_3_sum", - "irradiation_window_3_mean", - "irradiation_window_3_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 + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "x1_window_2_max": [None, None, None, None, 2.0, 4.0, 7.0], + "x2_window_2_max": [None, None, None, None, 20, 30, 40], + } - with pytest.raises(ValueError): - # get error when a user passes a string instead of list - tr.get_feature_names_out(input_features=["ambient_temp"]) - with pytest.raises(ValueError): - # assert error when uses passes features that were not transformed - tr.get_feature_names_out(input_features=["color"]) +def test_min_periods(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=3, min_periods=1).fit_transform(X) - # case 2: 1 window, 1 variable, multiple functions - tr = WindowFeatures( - variables="ambient_temp", window=2, functions=["sum", "mean", "count"] - ) - tr.fit(df_time) + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "x1_window_3_mean": pytest.approx( + [None, 1.0, 1.5, 7 / 3, 13 / 3, 22 / 3, 34 / 3] + ), + "x2_window_3_mean": [None, 10.0, 15.0, 20.0, 30.0, 40.0, 50.0], + } - # expected - output = [ - "ambient_temp_window_2_sum", - "ambient_temp_window_2_mean", - "ambient_temp_window_2_count", - ] - output = original_features + output - assert tr.get_feature_names_out(input_features=None) == output - assert tr.get_feature_names_out(input_features=df_time.columns) == output - - # case 3: multiple windows, multiple variables, multiple functions - tr = WindowFeatures(window=[2, 3], functions=["mean", "sum"]) - tr.fit(df_time) - - # expected - output = [ - "ambient_temp_window_2_mean", - "ambient_temp_window_2_sum", - "module_temp_window_2_mean", - "module_temp_window_2_sum", - "irradiation_window_2_mean", - "irradiation_window_2_sum", - "ambient_temp_window_3_mean", - "ambient_temp_window_3_sum", - "module_temp_window_3_mean", - "module_temp_window_3_sum", - "irradiation_window_3_mean", - "irradiation_window_3_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 - - # case 4: 1 window, multiple variables, 1 function - tr = WindowFeatures(window=2, functions=["mean"]) - tr.fit(df_time) - - # expected - output = [ - "ambient_temp_window_2_mean", - "module_temp_window_2_mean", - "irradiation_window_2_mean", - ] - output = original_features + output - assert tr.get_feature_names_out(input_features=None) == output - - # case 5: When function is a string - tr = WindowFeatures(window=2, functions="mean") - tr.fit(df_time) - - # expected - output = [ - "ambient_temp_window_2_mean", - "module_temp_window_2_mean", - "irradiation_window_2_mean", - ] - 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 - - # case 6: drop_original is True - tr = WindowFeatures(window=2, functions="mean", drop_original=True) - tr.fit(df_time) - - # expected - output = [ - "ambient_temp_window_2_mean", - "module_temp_window_2_mean", - "irradiation_window_2_mean", - ] - assert tr.get_feature_names_out(input_features=None) == ["color"] + output - assert ( - tr.get_feature_names_out(input_features=original_features) == ["color"] + output - ) +def test_min_periods_with_multiple_windows(make_df): + X = make_df(DATA) + Xt = WindowFeatures(variables="x2", window=[2, 3], min_periods=2).fit_transform(X) -def test_single_window_when_using_periods(df_time): - - expected_results = { - "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68, 33.76], - "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61, 47.01, 46.67, 47.52, 49.8], - "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42, 0.49, 0.57, 0.56, 0.74], - "color": [ - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - ], - "ambient_temp_window_3_median": [ - np.nan, - np.nan, - np.nan, - np.nan, - 31.51, - 32.15, - 32.39, - 32.5, - 32.52, - ], - "module_temp_window_3_median": [ - np.nan, - np.nan, - np.nan, - np.nan, - 49.84, - 50.63, - 50.63, - 49.61, - 47.01, - ], - "irradiation_window_3_median": [ - np.nan, - np.nan, - np.nan, - np.nan, - 0.65, - 0.76, - 0.65, - 0.49, - 0.49, - ], + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + **DATA, + "x2_window_2_mean": [None, None, 15.0, 25.0, 35.0, 45.0, 55.0], + "x2_window_3_mean": [None, None, 15.0, 20.0, 30.0, 40.0, 50.0], } - expected_results_df = pd.DataFrame(data=expected_results, index=_date_time) - - # Case 1: automatically select variables - transformer = WindowFeatures(window=3, functions=["median"], periods=2) - df_tr = transformer.fit_transform(df_time) - assert df_tr.head(9).equals(expected_results_df) - # Case 2: when drop_original is true +@pytest.mark.parametrize( + "min_periods, mean, count", + [ + ( + None, + [None, None, None, None, None, None, 34 / 3], + [None, None, None, 2.0, 2.0, 2.0, 3.0], + ), + ( + 2, + [None, None, 1.5, 1.5, 4.5, 9.0, 34 / 3], + [None, None, 2.0, 2.0, 2.0, 2.0, 3.0], + ), + ], +) +def test_missing_values_ignored(make_df, min_periods, mean, count): + X = make_df({**DATA, "x1": [1.0, 2.0, None, 7.0, 11.0, 16.0, 22.0]}) transformer = WindowFeatures( - window=3, functions=["median"], periods=2, drop_original=True + variables="x1", + functions=["mean", "count"], + min_periods=min_periods, + missing_values="ignore", ) - df_tr = transformer.fit_transform(df_time) + Xt = transformer.fit_transform(X) - assert df_tr.head(9).equals( - expected_results_df.drop(["ambient_temp", "module_temp", "irradiation"], axis=1) - ) + assert isinstance(Xt, make_df) + # windows with missing data need min_periods rows with data + assert frame_to_dict(Xt)["x1_window_3_mean"] == pytest.approx(mean) + assert frame_to_dict(Xt)["x1_window_3_count"] == count - # Case 3: user indicates multiple variables - transformer = WindowFeatures( - variables=["module_temp", "irradiation"], - window=3, - functions="median", - periods=2, - ) - transformer.fit(df_time) - df_tr = transformer.transform(df_time) - assert df_tr.head(9).equals( - expected_results_df.drop(["ambient_temp_window_3_median"], axis=1) - ) +def test_drop_original(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=2, drop_original=True).fit_transform(X) - # Case 4: user indicates 1 variable - transformer = WindowFeatures( - variables=["module_temp"], window=3, functions=["median"], periods=2 - ) - transformer.fit(df_time) - df_tr = transformer.transform(df_time) + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "cat": DATA["cat"], + "x1_window_2_mean": [None, None, 1.5, 3.0, 5.5, 9.0, 13.5], + "x2_window_2_mean": [None, None, 15.0, 25.0, 35.0, 45.0, 55.0], + } - assert df_tr.head(9).equals( - expected_results_df.drop( - ["ambient_temp_window_3_median", "irradiation_window_3_median"], axis=1 - ) - ) +def test_drop_na(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=[2, 4], functions="min", drop_na=True).fit_transform(X) -def test_single_window_when_using_freq(df_time): - - expected_results = { - "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68, 33.76], - "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61, 47.01, 46.67, 47.52, 49.8], - "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42, 0.49, 0.57, 0.56, 0.74], - "color": [ - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - "blue", - ], - "ambient_temp_window_2_sum": [ - np.nan, - np.nan, - np.nan, - np.nan, - 62.82, - 63.66, - 64.54, - 65.01, - 65.12, - ], - "module_temp_window_2_sum": [ - np.nan, - np.nan, - np.nan, - np.nan, - 99.02, - 102.19, - 102.98, - 100.24, - 96.62, - ], - "irradiation_window_2_sum": [ - np.nan, - np.nan, - np.nan, - np.nan, - 1.3, - 1.44, - 1.41, - 1.18, - 0.91, - ], + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "x1": [11.0, 16.0, 22.0], + "x2": [50, 60, 70], + "cat": ["e", "f", "g"], + "x1_window_2_min": [4.0, 7.0, 11.0], + "x2_window_2_min": [30, 40, 50], + "x1_window_4_min": [1.0, 2.0, 4.0], + "x2_window_4_min": [10, 20, 30], } - expected_results_df = pd.DataFrame(data=expected_results, index=_date_time) - # Case 1: automatically select variables - transformer = WindowFeatures(window=2, functions=["sum"], freq="45min") - df_tr = transformer.fit_transform(df_time) +def test_transform_x_y(make_df): + X = make_df(DATA) + y = make_series(make_df, [1, 2, 3, 4, 5, 6, 7], name="y") + transformer = WindowFeatures(window=4, drop_na=True).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) == [5, 6, 7] - assert df_tr.head(9).round(3).equals(expected_results_df) - # Case 2: when drop_original is true +def test_return_empty_without_numerical_variables(make_df): + X = make_df({"cat": DATA["cat"]}) transformer = WindowFeatures( - window=2, functions=["sum"], freq="45min", drop_original=True + window=[2, 3], functions=["mean", "max"], return_empty=True ) - df_tr = transformer.fit_transform(df_time) - - assert ( - df_tr.head(9) - .round(3) - .equals( - expected_results_df.drop( - ["ambient_temp", "module_temp", "irradiation"], axis=1 - ) - ) + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == {"cat": DATA["cat"]} + + +# pandas: the index orders the rows in time and allows time spans and freq +@pytest.fixture +def df_time_expected(): + return pd.DataFrame( + { + "ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68], + "module_temp": [49.18, 49.84, 52.35, 50.63, 49.61, 47.01, 46.67, 47.52], + "irradiation": [0.51, 0.79, 0.65, 0.76, 0.42, 0.49, 0.57, 0.56], + "color": ["blue"] * 8, + }, + index=pd.date_range("2020-05-15 12:00:00", periods=8, freq="15min"), ) - # Case 3: user indicates multiple variables + +def test_freq_with_pandas(df_time, df_time_expected): transformer = WindowFeatures( variables=["ambient_temp", "irradiation"], window=2, functions="sum", freq="45min", ) - df_tr = transformer.fit_transform(df_time) + Xt = transformer.fit_transform(df_time).head(8) - assert ( - df_tr.head(9) - .round(3) - .equals(expected_results_df.drop(["module_temp_window_2_sum"], axis=1)) + expected = df_time_expected.assign( + ambient_temp_window_2_sum=[np.nan] * 4 + [62.82, 63.66, 64.54, 65.01], + irradiation_window_2_sum=[np.nan] * 4 + [1.3, 1.44, 1.41, 1.18], ) + pd.testing.assert_frame_equal(Xt, expected, check_freq=False) - # Case 4: user indicates 1 variable - transformer = WindowFeatures( - variables=["irradiation"], window=2, functions=["sum"], freq="45min" - ) - df_tr = transformer.fit_transform(df_time) - - assert ( - df_tr.head(9) - .round(3) - .equals( - expected_results_df.drop( - ["ambient_temp_window_2_sum", "module_temp_window_2_sum"], axis=1 - ) - ) - ) - - -def test_multiple_windows(df_time): - # Case 1: automatically select variables +def test_time_span_windows_with_pandas(df_time, df_time_expected): transformer = WindowFeatures( - window=[2, 3], functions=["sum", "mean"], periods=15, freq="min" + variables="irradiation", window=["30min", "45min"], functions="max" ) - df_time_tr = transformer.fit_transform(df_time) - - # Expected - X = df_time.copy() - num_vars = ["ambient_temp", "module_temp", "irradiation"] - tmp = X[num_vars].rolling(2).agg(["sum", "mean"]).shift(periods=15, freq="min") - tmp.columns = tmp.columns.droplevel() - X_tr = X.merge(tmp, left_index=True, right_index=True, how="left") - tmp = X[num_vars].rolling(3).agg(["sum", "mean"]).shift(periods=15, freq="min") - tmp.columns = tmp.columns.droplevel() - X_tr = X_tr.merge(tmp, left_index=True, right_index=True, how="left") - X_tr.columns = transformer.get_feature_names_out() - - assert df_time_tr.equals(X_tr) - - # Case 2: user indicates multiple variables - transformer = WindowFeatures( - variables=["ambient_temp", "irradiation"], - window=[2, 3], - functions=["sum", "mean"], - freq="30min", - ) - df_time_tr = transformer.fit_transform(df_time) - - # Expected - X = df_time.copy() - tmp = ( - X[["ambient_temp", "irradiation"]] - .rolling(2) - .agg(["sum", "mean"]) - .shift(freq="30min") - ) - tmp.columns = tmp.columns.droplevel() - X_tr = X.merge(tmp, left_index=True, right_index=True, how="left") - tmp = ( - X[["ambient_temp", "irradiation"]] - .rolling(3) - .agg(["sum", "mean"]) - .shift(freq="30min") - ) - tmp.columns = tmp.columns.droplevel() - X_tr = X_tr.merge(tmp, left_index=True, right_index=True, how="left") - X_tr.columns = transformer.get_feature_names_out() + Xt = transformer.fit_transform(df_time).head(8) - assert df_time_tr.equals(X_tr) - - # Case 4: user indicates 1 variable - transformer = WindowFeatures( - variables=["irradiation"], - window=[2, 3], - functions="std", - periods=1, + # windows of time spans take the rows available + expected = df_time_expected.assign( + irradiation_window_30min_max=[np.nan, 0.51, 0.79, 0.79, 0.76, 0.76, 0.49, 0.57], + irradiation_window_45min_max=[np.nan, 0.51, 0.79, 0.79, 0.79, 0.76, 0.76, 0.57], ) - df_time_tr = transformer.fit_transform(df_time) - - # Expected - X = df_time.copy() - tmp = X["irradiation"].rolling(2).agg("std").shift(periods=1) - X_tr = X.merge(tmp, left_index=True, right_index=True, how="left") - tmp = X["irradiation"].rolling(3).agg("std").shift(periods=1) - X_tr = X_tr.merge(tmp, left_index=True, right_index=True, how="left") - X_tr.columns = transformer.get_feature_names_out() - - assert df_time_tr.equals(X_tr) + pd.testing.assert_frame_equal(Xt, expected, check_freq=False) -def test_min_periods_is_used(df_time): - # min_periods was accepted and documented but never reached pandas - # rolling(), so the leading rows stayed NaN whatever the user asked for. - variables = ["ambient_temp", "module_temp", "irradiation"] +def test_functions_only_in_pandas(df_time): + transformer = WindowFeatures(variables="irradiation", functions=["sem", "last"]) + Xt = transformer.fit_transform(df_time) - transformer = WindowFeatures(window=3, min_periods=1) - df_tr = transformer.fit_transform(df_time) + expected = df_time["irradiation"].rolling(3).agg(["sem", "last"]).shift(1) + expected.columns = ["irradiation_window_3_sem", "irradiation_window_3_last"] + pd.testing.assert_frame_equal(Xt[expected.columns], expected) - expected = ( - df_time[variables].rolling(window=3, min_periods=1).agg("mean").shift(periods=1) - ) - expected.columns = [f"{var}_window_3_mean" for var in variables] - assert_frame_equal(df_tr[expected.columns], expected) +def test_sort_index_with_pandas(df_time): + X = df_time.sample(frac=1, random_state=1) - # with min_periods=1 only the very first row (shifted out) remains NaN - assert df_tr["ambient_temp_window_3_mean"].isna().sum() == 1 + Xt = WindowFeatures(sort_index=True).fit_transform(X) + pd.testing.assert_frame_equal(Xt, WindowFeatures().fit_transform(df_time)) - # the default is unchanged: pandas requires a full window - df_default = WindowFeatures(window=3).fit_transform(df_time) - assert df_default["ambient_temp_window_3_mean"].isna().sum() == 3 + transformer = WindowFeatures(sort_index=False) + Xt = transformer.fit_transform(X) + pd.testing.assert_frame_equal(Xt[df_time.columns], X) -def test_min_periods_is_used_with_multiple_windows(df_time): - transformer = WindowFeatures(window=[2, 3], min_periods=1) - df_tr = transformer.fit_transform(df_time) +def test_transform_x_y_aligns_y_on_the_index_with_pandas(df_time): + X = df_time.sample(frac=1, random_state=1) + y = pd.Series(np.arange(len(X)), index=X.index) + transformer = WindowFeatures(window="45min", drop_na=True).fit(X) - for win in (2, 3): - expected = ( - df_time["ambient_temp"].rolling(window=win, min_periods=1).mean().shift(1) - ) - assert_frame_equal( - df_tr[[f"ambient_temp_window_{win}_mean"]], - expected.to_frame(f"ambient_temp_window_{win}_mean"), - ) + Xt, yt = transformer.transform_x_y(X, y) + pd.testing.assert_frame_equal(Xt, transformer.transform(X)) + pd.testing.assert_series_equal(yt, y.loc[Xt.index]) -def test_sort_index(df_time): - # Shuffle dataframe - Xs = df_time.copy() - Xs = Xs.sample(frac=1) - transformer = WindowFeatures(sort_index=False) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal(df_tr[transformer.variables_], Xs[transformer.variables_]) +def test_integer_column_names_with_pandas(): + X = pd.DataFrame({0: DATA["x1"], 1: DATA["x2"], "cat": DATA["cat"]}) + transformer = WindowFeatures(window=[2, 3], drop_original=True, drop_na=True) + Xt = transformer.fit_transform(X) - transformer = WindowFeatures(sort_index=True) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal( - df_tr[transformer.variables_], Xs[transformer.variables_].sort_index() + expected = pd.DataFrame( + { + "cat": ["d", "e", "f", "g"], + "0_window_2_mean": [3.0, 5.5, 9.0, 13.5], + "1_window_2_mean": [25.0, 35.0, 45.0, 55.0], + "0_window_3_mean": [7 / 3, 13 / 3, 22 / 3, 34 / 3], + "1_window_3_mean": [20.0, 30.0, 40.0, 50.0], + }, + index=[3, 4, 5, 6], ) + # 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_drop_na(df_time): - df = df_time.head(9).copy() - - expected_results = { - "ambient_temp": [32.62, 32.5, 32.52, 32.68, 33.76], - "module_temp": [49.61, 47.01, 46.67, 47.52, 49.8], - "irradiation": [0.42, 0.49, 0.57, 0.56, 0.74], - "color": [ - "blue", - "blue", - "blue", - "blue", - "blue", - ], - "ambient_temp_window_3_median": [ - 31.51, - 32.15, - 32.39, - 32.5, - 32.52, - ], - "module_temp_window_3_median": [ - 49.84, - 50.63, - 50.63, - 49.61, - 47.01, - ], - "irradiation_window_3_median": [ - 0.65, - 0.76, - 0.65, - 0.49, - 0.49, - ], - } - expected_results_df = pd.DataFrame(data=expected_results, index=_date_time[4:]) +# polars: the rows are used in the order given and the windows are numbers of rows +def test_rows_keep_their_order_with_polars(): + X = pl.DataFrame({"x1": [4.0, 1.0, 7.0, 2.0]}) + Xt = WindowFeatures(window=2, functions="max").fit_transform(X) - # Case 1: automatically select variables - transformer = WindowFeatures( - window=3, functions=["median"], periods=2, drop_na=True - ) - df_tr = transformer.fit_transform(df) - - assert df_tr.equals(expected_results_df) + assert frame_to_dict(Xt)["x1_window_2_max"] == [None, None, 4.0, 7.0] - # Case 2: when drop_original is true - transformer = WindowFeatures( - window=3, - functions=["median"], - periods=2, - drop_original=True, - drop_na=True, - ) - df_tr = transformer.fit_transform(df) - assert df_tr.equals( - expected_results_df.drop(["ambient_temp", "module_temp", "irradiation"], axis=1) +@pytest.mark.parametrize("window", ["3D", ["45min", "30min"], [2, "30min"]]) +def test_error_if_time_span_window_with_polars(window): + msg = ( + "Time spans in window, like '3D', are only supported with pandas " + "dataframes, because they use the dataframe's DatetimeIndex. With other " + "dataframes, window takes integers, the number of rows in each window. " + f"Got {window} instead." ) + with pytest.raises(NotImplementedError, match=re.escape(msg)): + WindowFeatures(window=window).fit(pl.DataFrame(DATA)) - # Case 3: user indicates multiple variables - transformer = WindowFeatures( - variables=["module_temp", "irradiation"], - window=3, - functions="median", - periods=2, - drop_na=True, + # a transformer fitted on pandas can't transform polars with time spans either + transformer = WindowFeatures(window=window).fit( + pd.DataFrame(DATA, index=pd.date_range("2020-01-01", periods=7)) ) - transformer.fit(df) - df_tr = transformer.transform(df) + with pytest.raises(NotImplementedError, match=re.escape(msg)): + transformer.transform(pl.DataFrame(DATA)) - assert df_tr.equals( - expected_results_df.drop(["ambient_temp_window_3_median"], axis=1) - ) +@pytest.mark.parametrize("functions", ["sem", ["mean", "last"]]) +def test_error_if_function_not_supported_with_polars(functions): + msg = MSG_POLARS_FUNCTIONS + f"Got {functions} instead." + with pytest.raises(NotImplementedError, match=re.escape(msg)): + WindowFeatures(functions=functions).fit(pl.DataFrame(DATA)) -def test_transform_x_y(df_time): - df = df_time.head(9).copy() - y = pd.Series(np.zeros(len(df)), index=df.index) - - expected_results = { - "ambient_temp": [32.62, 32.5, 32.52, 32.68, 33.76], - "module_temp": [49.61, 47.01, 46.67, 47.52, 49.8], - "irradiation": [0.42, 0.49, 0.57, 0.56, 0.74], - "color": [ - "blue", - "blue", - "blue", - "blue", - "blue", - ], - "ambient_temp_window_3_median": [ - 31.51, - 32.15, - 32.39, - 32.5, - 32.52, - ], - "module_temp_window_3_median": [ - 49.84, - 50.63, - 50.63, - 49.61, - 47.01, - ], - "irradiation_window_3_median": [ - 0.65, - 0.76, - 0.65, - 0.49, - 0.49, - ], - } - expected_results_df = pd.DataFrame(data=expected_results, index=_date_time[4:]) - transformer = WindowFeatures( - window=3, functions=["median"], periods=2, drop_na=True - ) + transformer = WindowFeatures(functions=functions).fit(pd.DataFrame(DATA)) + with pytest.raises(NotImplementedError, match=re.escape(msg)): + transformer.transform(pl.DataFrame(DATA)) - df_tr = transformer.fit_transform(df) - assert df_tr.equals(expected_results_df) - assert len(df_tr) != len(y) +def test_error_if_min_periods_is_zero_with_polars(): + msg = ( + "min_periods=0 is only supported with pandas dataframes. With other " + "dataframes, min_periods takes integers greater than 0 or None. " + "Got 0 instead." + ) + with pytest.raises(NotImplementedError, match=re.escape(msg)): + WindowFeatures(min_periods=0).fit(pl.DataFrame(DATA)) - Xt, yt = transformer.transform_x_y(df, y) - assert len(Xt) == len(yt) - assert len(y) != len(yt) - assert (Xt.index == yt.index).all() + transformer = WindowFeatures(min_periods=0).fit(pd.DataFrame(DATA)) + with pytest.raises(NotImplementedError, match=re.escape(msg)): + transformer.transform(pl.DataFrame(DATA)) From f9c373ab3b17a7fa4a18cfd3090de3e9e39b527f Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Sat, 19 Sep 2026 12:50:15 +0200 Subject: [PATCH 2/7] Mark polars output blocks in the user guide as text Co-Authored-By: Claude Opus 5 --- docs/user_guide/timeseries/forecasting/WindowFeatures.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user_guide/timeseries/forecasting/WindowFeatures.rst b/docs/user_guide/timeseries/forecasting/WindowFeatures.rst index ddec26a5d..5ca3624a5 100644 --- a/docs/user_guide/timeseries/forecasting/WindowFeatures.rst +++ b/docs/user_guide/timeseries/forecasting/WindowFeatures.rst @@ -649,7 +649,7 @@ Windows of 2 and 4 rows cover 30 and 60 minutes of data: We see the window features on the right of the dataframe. The first rows, which don't have enough past data to fill the window, contain null values: -.. code:: python +.. code:: text shape: (8, 6) ┌──────────────┬─────────────┬─────────────────┬─────────────────┬────────────────┬────────────────┐ From 815f32396ce8e9f20f598ba36d1a5eeaaff236be Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Sat, 21 Nov 2026 10:18:35 +0100 Subject: [PATCH 3/7] move WindowFeatures to check_X and the forecasting helpers Co-Authored-By: Claude Opus 5.5 --- .../forecasting/_forecasting_helpers.py | 165 ++++++++++++++++ .../timeseries/forecasting/window_features.py | 185 +++++------------- .../test_forecasting_helpers.py | 29 +++ .../test_forecasting/test_window_features.py | 15 -- 4 files changed, 242 insertions(+), 152 deletions(-) diff --git a/feature_engine/timeseries/forecasting/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index 006640a1b..cc1d6b5bf 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -9,6 +9,7 @@ narwhals dataframe for the other libraries. """ +from itertools import product from typing import Any, List, Optional, Sequence, Union import narwhals as nw @@ -16,6 +17,34 @@ DataFrame = Union[IntoDataFrame, nw.DataFrame] +# pandas' rolling functions that other dataframes support: with narwhals, or with +# polars' own expressions when narwhals has none (they are faster than numpy). +_NW_ROLLING = { + "count": lambda col, win, min_samples: (~col.is_null()) + .cast(nw.Float64) + .rolling_sum(win, min_samples=min_samples), + "mean": lambda col, win, min_samples: col.rolling_mean( + win, min_samples=min_samples + ), + "std": lambda col, win, min_samples: col.rolling_std(win, min_samples=min_samples), + "sum": lambda col, win, min_samples: col.rolling_sum(win, min_samples=min_samples), + "var": lambda col, win, min_samples: col.rolling_var(win, min_samples=min_samples), +} +_POLARS_ROLLING = { + # bias=False gives the sample skewness and kurtosis, as pandas. + "kurt": lambda col, win, min_samples: col.rolling_kurtosis( + win, bias=False, min_samples=min_samples + ), + "max": lambda col, win, min_samples: col.rolling_max(win, min_samples=min_samples), + "median": lambda col, win, min_samples: col.rolling_median( + win, min_samples=min_samples + ), + "min": lambda col, win, min_samples: col.rolling_min(win, min_samples=min_samples), + "skew": lambda col, win, min_samples: col.rolling_skew( + win, bias=False, min_samples=min_samples + ), +} + def check_index(X: DataFrame, freq: Any = None) -> None: """ @@ -155,3 +184,139 @@ def add_lag_features( ) return X + + +def check_window_parameters( + X: DataFrame, + window: Any, + functions: Union[str, List[str]], + min_periods: Optional[int], +) -> None: + """ + Checks that dataframes without an index use windows of rows, and functions and + min_periods that they support. + + Parameters + ---------- + X : pandas or narwhals dataframe + The dataframe returned by `check_X`. + + window : int, str or list + The `window` parameter of WindowFeatures. + + functions : str or list + The `functions` parameter of WindowFeatures. + + min_periods : int or None + The minimum number of values in a window to return a value. + """ + # only pandas has an index, and pandas supports every window. + if not isinstance(X, nw.DataFrame): + return + + windows = window if isinstance(window, list) else [window] + if not all(isinstance(win, int) for win in windows): + raise NotImplementedError( + "Time spans in window, like '3D', are only supported with pandas " + "dataframes, because they use the dataframe's DatetimeIndex. With " + "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] + if not all( + function in _NW_ROLLING or function in _POLARS_ROLLING + for function in function_list + ): + raise NotImplementedError( + "With dataframes other than pandas, functions takes only " + f"{sorted([*_NW_ROLLING, *_POLARS_ROLLING])}. Got {functions} instead." + ) + if min_periods == 0: + raise NotImplementedError( + "min_periods=0 is only supported with pandas dataframes. With " + "other dataframes, min_periods takes integers greater than 0 or " + f"None. Got {min_periods} instead." + ) + + +def add_window_features( + X: DataFrame, + variables: Sequence[Union[str, int]], + windows: List[Any], + functions: List[str], + min_periods: Optional[int], + periods: int, + freq: Optional[str], + names: List[str], +) -> DataFrame: + """ + Adds functions of the values in a window of past rows, 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. + + windows : list + The window sizes: numbers of rows, or time spans with pandas. + + functions : list + The functions to apply to each window. + + min_periods : int or None + The minimum number of values in a window to return a value. If None, the + window size. + + periods : int + The number of rows to shift the windows by, so they hold past values only. + + freq : str or None + The time span to shift the pandas index by, instead of `periods`. + + names : list + The names of the new features: for each window, variable and function. + + Returns + ------- + X : pandas or narwhals dataframe + The dataframe with the new features. + """ + # pandas is faster than narwhals, and time spans and freq need its index. + name_of = dict(zip(product(windows, variables, functions), names)) + if not isinstance(X, nw.DataFrame): + tmp = [] + for win in windows: + rolling = X[list(variables)].rolling(window=win, min_periods=min_periods) + for function in functions: + # the rolling methods are faster than agg() with many variables. + rolled = getattr(rolling, function)().shift(periods=periods, freq=freq) + rolled.columns = [name_of[(win, var, function)] for var in variables] + tmp.append(rolled) + # with freq, the index of the features moves: merge aligns them to X. + return X.merge( + tmp[0].join(tmp[1:])[names], left_index=True, right_index=True, how="left" + ) + + plx = nw.get_native_namespace(X) + nw_exprs, native_exprs = [], [] + for (win, var, function), name in name_of.items(): + # like pandas, windows of integers need all their rows by default. + min_samples = win if min_periods is None else min_periods + if function in _NW_ROLLING: + rolled = _NW_ROLLING[function](nw.col(var), win, min_samples) + nw_exprs.append(rolled.shift(periods).alias(name)) + else: + rolled = _POLARS_ROLLING[function](plx.col(var), win, min_samples) + native_exprs.append(rolled.shift(periods).alias(name)) + + columns = X.columns + X = X.with_columns(nw_exprs) + if len(native_exprs) > 0: + # the polars features were added last: restore the order of the names. + X_pl = X.to_native().with_columns(native_exprs) + X = nw.from_native(X_pl, eager_only=True).select(columns + names) + return X diff --git a/feature_engine/timeseries/forecasting/window_features.py b/feature_engine/timeseries/forecasting/window_features.py index 3fb9733b6..4c8d76360 100644 --- a/feature_engine/timeseries/forecasting/window_features.py +++ b/feature_engine/timeseries/forecasting/window_features.py @@ -1,9 +1,7 @@ -from itertools import product -from typing import Callable, List, Union +from typing import Callable, List, Optional, Union 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, @@ -20,38 +18,20 @@ _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_window_features, + check_window_parameters, +) from feature_engine.timeseries.forecasting.base_forecast_transformers import ( BaseForecastTransformer, ) -# pandas' rolling functions that other dataframes support: with narwhals, or with -# polars' own expressions when narwhals has none (they are faster than numpy). -_NW_ROLLING = { - "count": lambda col, win, min_samples: (~col.is_null()) - .cast(nw.Float64) - .rolling_sum(win, min_samples=min_samples), - "mean": lambda col, win, min_samples: col.rolling_mean( - win, min_samples=min_samples - ), - "std": lambda col, win, min_samples: col.rolling_std(win, min_samples=min_samples), - "sum": lambda col, win, min_samples: col.rolling_sum(win, min_samples=min_samples), - "var": lambda col, win, min_samples: col.rolling_var(win, min_samples=min_samples), -} -_POLARS_ROLLING = { - # bias=False gives the sample skewness and kurtosis, as pandas. - "kurt": lambda col, win, min_samples: col.rolling_kurtosis( - win, bias=False, min_samples=min_samples - ), - "max": lambda col, win, min_samples: col.rolling_max(win, min_samples=min_samples), - "median": lambda col, win, min_samples: col.rolling_median( - win, min_samples=min_samples - ), - "min": lambda col, win, min_samples: col.rolling_min(win, min_samples=min_samples), - "skew": lambda col, win, min_samples: col.rolling_skew( - win, bias=False, min_samples=min_samples - ), -} - @Substitution( variables=_variables_numerical_docstring, @@ -258,49 +238,22 @@ def __init__( self.freq = freq self.sort_index = sort_index - def _check_index(self, X: IntoDataFrame): + def fit(self, X: IntoDataFrame, y: Optional[IntoSeries] = None): """ - Checks that the rows of the dataframe can be ordered in time and, with - dataframes other than pandas, that `window`, `functions` and `min_periods` - are supported. + This transformer does not learn parameters. Parameters ---------- X: dataframe of shape = [n_samples, n_features] - The dataset. - """ - super()._check_index(X) - - if nwd.is_pandas_dataframe(X) is False: - windows = self.window if isinstance(self.window, list) else [self.window] - if not all(isinstance(win, int) for win in windows): - raise NotImplementedError( - "Time spans in window, like '3D', are only supported with pandas " - "dataframes, because they use the dataframe's DatetimeIndex. With " - "other dataframes, window takes integers, the number of rows in " - f"each window. Got {self.window} instead." - ) - - functions = ( - self.functions if isinstance(self.functions, list) else [self.functions] - ) - if not all( - function in _NW_ROLLING or function in _POLARS_ROLLING - for function in functions - ): - raise NotImplementedError( - "With dataframes other than pandas, functions takes only " - f"{sorted([*_NW_ROLLING, *_POLARS_ROLLING])}. " - f"Got {self.functions} instead." - ) - - if self.min_periods == 0: - raise NotImplementedError( - "min_periods=0 is only supported with pandas dataframes. With " - "other dataframes, min_periods takes integers greater than 0 or " - f"None. Got {self.min_periods} instead." - ) + 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_window_parameters( + check_X(X), self.window, self.functions, self.min_periods + ) return self def transform(self, X: IntoDataFrame) -> IntoDataFrame: @@ -318,82 +271,40 @@ def transform(self, X: IntoDataFrame) -> IntoDataFrame: 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) + X = self._check_transform_input_and_state(X) - def _add_features(self, nw_X: nw.DataFrame) -> nw.DataFrame: - """ - Adds the window features after the columns of `nw_X`. + if len(self.variables_) > 0: + windows = self.window if isinstance(self.window, list) else [self.window] + X = add_window_features( + X, + self.variables_, + windows, + self._functions_list(), + self.min_periods, + self.periods, + self.freq, + self._get_new_features_name(), + ) - Parameters - ---------- - nw_X: narwhals dataframe of shape = [n_samples, n_features] - The data returned by `_check_transform_input_and_state()`. - """ - if len(self.variables_) == 0: - return nw_X + if self.drop_original is True: + X = drop_variables_from_df(X, self.variables_) - windows = self.window if isinstance(self.window, list) else [self.window] - functions = ( - self.functions if isinstance(self.functions, list) else [self.functions] - ) - new_features = self._get_new_features_name() - X = nw_X.to_native() - - if nwd.is_pandas_dataframe(X) is True: - # pandas is faster than narwhals, and time spans and freq need its index. - tmp = [] - for win in windows: - rolling = X[self.variables_].rolling( - window=win, min_periods=self.min_periods - ) - for function in functions: - # the rolling methods are faster than agg() with many variables. - rolled = getattr(rolling, function)().shift( - periods=self.periods, freq=self.freq - ) - rolled.columns = [ - f"{var}_window_{win}_{function}" for var in self.variables_ - ] - tmp.append(rolled) - # with freq, the index of the features moves: merge aligns them to X. - X = X.merge( - tmp[0].join(tmp[1:])[new_features], - left_index=True, - right_index=True, - how="left", - ) - return nw.from_native(X, eager_only=True) + if self.drop_na is True: + new_features = self._get_new_features_name() + X = filter_rows(X, ~rows_with_missing_values(X, new_features)) - plx = nw.get_native_namespace(nw_X) - nw_exprs, native_exprs = [], [] - for name, (win, var, function) in zip( - new_features, product(windows, self.variables_, functions) - ): - # like pandas, windows of integers need all their rows by default. - min_samples = win if self.min_periods is None else self.min_periods - if function in _NW_ROLLING: - rolled = _NW_ROLLING[function](nw.col(var), win, min_samples) - nw_exprs.append(rolled.shift(self.periods).alias(name)) - else: - rolled = _POLARS_ROLLING[function](plx.col(var), win, min_samples) - native_exprs.append(rolled.shift(self.periods).alias(name)) - - columns = nw_X.columns - nw_X = nw_X.with_columns(nw_exprs) - if len(native_exprs) > 0: - # the polars features were added last: restore the order of the names. - X = nw_X.to_native().with_columns(native_exprs) - nw_X = nw.from_native(X, eager_only=True).select(columns + new_features) - - return nw_X + 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 lag features.""" - if not isinstance(self.functions, list): - functions_ = [self.functions] - else: - functions_ = self.functions + functions_ = self._functions_list() if isinstance(self.window, list): feature_names = [ 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 c274554ce..cd7944201 100644 --- a/tests/test_time_series/test_forecasting/test_forecasting_helpers.py +++ b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py @@ -8,7 +8,9 @@ from feature_engine.dataframe_checks import check_X from feature_engine.timeseries.forecasting._forecasting_helpers import ( add_lag_features, + add_window_features, check_index, + check_window_parameters, sort_by_index, ) from tests.backend_helpers import frame_to_dict @@ -103,3 +105,30 @@ def test_add_lag_features_with_fill_value(backend): 1.0, None, ] + + +def test_add_window_features(make_df): + X = check_X(make_df({"a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0]})) + names = ["a_max", "a_mean", "b_max", "b_mean"] + Xt = add_window_features(X, ["a", "b"], [2], ["max", "mean"], None, 1, None, names) + + # max and mean come from different libraries with polars, in the order of names + assert frame_to_dict(nw.to_native(Xt, pass_through=True)) == { + "a": [1.0, 2.0, 3.0, 4.0], + "b": [4.0, 3.0, 2.0, 1.0], + "a_max": [None, None, 2.0, 3.0], + "a_mean": [None, None, 1.5, 2.5], + "b_max": [None, None, 4.0, 3.0], + "b_mean": [None, None, 3.5, 2.5], + } + + +@pytest.mark.parametrize( + "window, functions, min_periods", + [("3D", "mean", None), (3, ["sem"], None), (3, "mean", 0)], +) +def test_check_window_parameters_accepts_everything_with_pandas( + window, functions, min_periods +): + X = check_X(pd.DataFrame({"a": [1, 2, 3]}, index=DATES)) + check_window_parameters(X, window, functions, min_periods) diff --git a/tests/test_time_series/test_forecasting/test_window_features.py b/tests/test_time_series/test_forecasting/test_window_features.py index 6c475e305..6a1d42238 100644 --- a/tests/test_time_series/test_forecasting/test_window_features.py +++ b/tests/test_time_series/test_forecasting/test_window_features.py @@ -403,13 +403,6 @@ def test_error_if_time_span_window_with_polars(window): with pytest.raises(NotImplementedError, match=re.escape(msg)): WindowFeatures(window=window).fit(pl.DataFrame(DATA)) - # a transformer fitted on pandas can't transform polars with time spans either - transformer = WindowFeatures(window=window).fit( - pd.DataFrame(DATA, index=pd.date_range("2020-01-01", periods=7)) - ) - with pytest.raises(NotImplementedError, match=re.escape(msg)): - transformer.transform(pl.DataFrame(DATA)) - @pytest.mark.parametrize("functions", ["sem", ["mean", "last"]]) def test_error_if_function_not_supported_with_polars(functions): @@ -417,10 +410,6 @@ def test_error_if_function_not_supported_with_polars(functions): with pytest.raises(NotImplementedError, match=re.escape(msg)): WindowFeatures(functions=functions).fit(pl.DataFrame(DATA)) - transformer = WindowFeatures(functions=functions).fit(pd.DataFrame(DATA)) - with pytest.raises(NotImplementedError, match=re.escape(msg)): - transformer.transform(pl.DataFrame(DATA)) - def test_error_if_min_periods_is_zero_with_polars(): msg = ( @@ -430,7 +419,3 @@ def test_error_if_min_periods_is_zero_with_polars(): ) with pytest.raises(NotImplementedError, match=re.escape(msg)): WindowFeatures(min_periods=0).fit(pl.DataFrame(DATA)) - - transformer = WindowFeatures(min_periods=0).fit(pd.DataFrame(DATA)) - with pytest.raises(NotImplementedError, match=re.escape(msg)): - transformer.transform(pl.DataFrame(DATA)) From c354c6c0c77351fc174e40c04b0dce4026c9a9f2 Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Wed, 25 Nov 2026 19:58:10 +0100 Subject: [PATCH 4/7] validate WindowFeatures parameters in init and simplify the window helper Co-Authored-By: Claude Opus 5.5 --- .../forecasting/_forecasting_helpers.py | 39 +++++++++-------- .../timeseries/forecasting/window_features.py | 43 +++++++++++++++---- .../test_forecasting/test_window_features.py | 42 +++++++++++++++--- 3 files changed, 91 insertions(+), 33 deletions(-) diff --git a/feature_engine/timeseries/forecasting/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index cc1d6b5bf..628797144 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -297,26 +297,27 @@ def add_window_features( rolled.columns = [name_of[(win, var, function)] for var in variables] tmp.append(rolled) # with freq, the index of the features moves: merge aligns them to X. - return X.merge( + X = X.merge( tmp[0].join(tmp[1:])[names], left_index=True, right_index=True, how="left" ) + else: + plx = nw.get_native_namespace(X) + nw_exprs, native_exprs = [], [] + for (win, var, function), name in name_of.items(): + # like pandas, windows of integers need all their rows by default. + min_samples = win if min_periods is None else min_periods + if function in _NW_ROLLING: + rolled = _NW_ROLLING[function](nw.col(var), win, min_samples) + nw_exprs.append(rolled.shift(periods).alias(name)) + else: + rolled = _POLARS_ROLLING[function](plx.col(var), win, min_samples) + native_exprs.append(rolled.shift(periods).alias(name)) + + columns = X.columns + X = X.with_columns(nw_exprs) + if len(native_exprs) > 0: + # the polars features were added last: restore the order of the names. + X_pl = X.to_native().with_columns(native_exprs) + X = nw.from_native(X_pl, eager_only=True).select(columns + names) - plx = nw.get_native_namespace(X) - nw_exprs, native_exprs = [], [] - for (win, var, function), name in name_of.items(): - # like pandas, windows of integers need all their rows by default. - min_samples = win if min_periods is None else min_periods - if function in _NW_ROLLING: - rolled = _NW_ROLLING[function](nw.col(var), win, min_samples) - nw_exprs.append(rolled.shift(periods).alias(name)) - else: - rolled = _POLARS_ROLLING[function](plx.col(var), win, min_samples) - native_exprs.append(rolled.shift(periods).alias(name)) - - columns = X.columns - X = X.with_columns(nw_exprs) - if len(native_exprs) > 0: - # the polars features were added last: restore the order of the names. - X_pl = X.to_native().with_columns(native_exprs) - X = nw.from_native(X_pl, eager_only=True).select(columns + names) return X diff --git a/feature_engine/timeseries/forecasting/window_features.py b/feature_engine/timeseries/forecasting/window_features.py index 4c8d76360..41ab55e2c 100644 --- a/feature_engine/timeseries/forecasting/window_features.py +++ b/feature_engine/timeseries/forecasting/window_features.py @@ -209,20 +209,47 @@ def __init__( drop_na: bool = False, ) -> None: - if isinstance(window, list) and len(window) != len(set(window)): - raise ValueError(f"There are duplicated windows in the list: {window}") + windows = window if isinstance(window, list) else [window] + # bool is a subclass of int, but True is not a window size. Windows that + # are not integers, like time spans, are checked by pandas. + if len(windows) == 0 or any( + isinstance(win, int) and (isinstance(win, bool) or win < 1) + for win in windows + ): + raise ValueError( + "window must be a positive integer, a time span or a non-empty list " + f"of them. Got {window} instead." + ) + if len(windows) != len(set(windows)): + raise ValueError( + f"There are duplicated windows in the list. Got {window} instead." + ) - 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( - f"functions must be a string or a list of strings. " + "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 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 < 1: + if not isinstance(periods, int) or isinstance(periods, bool) or periods < 1: raise ValueError( f"periods must be a positive integer. Got {periods} instead." ) @@ -302,7 +329,7 @@ def _functions_list(self) -> List[str]: return [self.functions] def _get_new_features_name(self) -> List: - """Get names of the lag features.""" + """Get names of the window features.""" functions_ = self._functions_list() diff --git a/tests/test_time_series/test_forecasting/test_window_features.py b/tests/test_time_series/test_forecasting/test_window_features.py index 6a1d42238..1cfcfbea2 100644 --- a/tests/test_time_series/test_forecasting/test_window_features.py +++ b/tests/test_time_series/test_forecasting/test_window_features.py @@ -21,27 +21,57 @@ # init parameters +@pytest.mark.parametrize("window", [0, -1, True, [], [3, 0], [2, False]]) +def test_error_if_window_not_permitted(window): + msg = ( + "window must be a positive integer, a time span or a non-empty list of " + f"them. Got {window} instead." + ) + with pytest.raises(ValueError, match=re.escape(msg)): + WindowFeatures(window=window) + + @pytest.mark.parametrize("window", [[2, 2, 3], ["45min", "45min", "30min"]]) def test_error_if_window_duplicated(window): - msg = f"There are duplicated windows in the list: {window}" + msg = f"There are duplicated windows in the list. Got {window} instead." with pytest.raises(ValueError, match=re.escape(msg)): WindowFeatures(window=window) -@pytest.mark.parametrize("functions", [3.33, [1, "mean"], None, ("mean", "sum")]) +@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)): + WindowFeatures(min_periods=min_periods) + + +@pytest.mark.parametrize( + "functions", [3.33, [1, "mean"], None, ("mean", "sum"), [], ""] +) def test_error_if_functions_not_string_or_list(functions): - msg = f"functions must be a string or a list of strings. 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)): WindowFeatures(functions=functions) def test_error_if_functions_duplicated(): - msg = "There are duplicated functions in the list: ['sum', 'sum', 'mean']" + msg = ( + "There are duplicated functions in the list. " + "Got ['sum', 'sum', 'mean'] instead." + ) with pytest.raises(ValueError, match=re.escape(msg)): WindowFeatures(functions=["sum", "sum", "mean"]) -@pytest.mark.parametrize("periods", ["pizza", 3.33, ["mate", "cumbia"], None, 0, -1]) +@pytest.mark.parametrize( + "periods", ["pizza", 3.33, ["mate", "cumbia"], None, 0, -1, True] +) def test_error_if_periods_not_positive_integer(periods): msg = f"periods must be a positive integer. Got {periods} instead." with pytest.raises(ValueError, match=re.escape(msg)): @@ -52,7 +82,7 @@ def test_error_if_periods_not_positive_integer(periods): "window, min_periods, functions, periods, freq, sort_index", [ (3, None, "mean", 1, None, True), - ([2, 3], 1, ["sum", "mean", "count"], 2, "15min", False), + ([2, 3], 0, ["sum", "mean", "count"], 2, "15min", False), (["45min", "30min"], 2, ["std"], 3, "1h", True), ], ) From 7d1fc09aa8736e3422bc661ca24483256c56bb2d Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Thu, 26 Nov 2026 14:55:24 +0100 Subject: [PATCH 5/7] support first, last, nunique, rank and sem in WindowFeatures with polars With polars, WindowFeatures now takes the 15 pandas rolling functions that aggregate one variable. sem uses narwhals, rank uses polars' rolling_rank, and first, last and nunique aggregate the rows of each window. The docstring and the user guide list the polars functions and link to the pandas ones. Co-Authored-By: Claude Opus 5.5 --- .../timeseries/forecasting/WindowFeatures.rst | 46 ++++++++++++++-- .../forecasting/_forecasting_helpers.py | 42 +++++++++++---- .../timeseries/forecasting/window_features.py | 13 +++-- .../test_forecasting_helpers.py | 9 ++-- .../test_forecasting/test_window_features.py | 52 ++++++++++++++----- 5 files changed, 129 insertions(+), 33 deletions(-) diff --git a/docs/user_guide/timeseries/forecasting/WindowFeatures.rst b/docs/user_guide/timeseries/forecasting/WindowFeatures.rst index 5ca3624a5..69cdf362a 100644 --- a/docs/user_guide/timeseries/forecasting/WindowFeatures.rst +++ b/docs/user_guide/timeseries/forecasting/WindowFeatures.rst @@ -80,8 +80,9 @@ can pass a list of integers, strings or functions, to perform computations over window sizes. :class:`WindowFeatures` performs the mathematical operations over the windows with the -methods of `pandas.rolling`. Therefore, you can use any operation supported -by pandas. For supported aggregation functions, see Rolling Window +methods of `pandas.rolling`. 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 Rolling Window `Functions `_. With `pandas.shift`, :class:`WindowFeatures` places the value derived from the past @@ -618,8 +619,10 @@ sorted in time before creating the features. For the same reason, with polars: - `window` takes the number of rows in each window, as an integer or a list of integers. Time spans, like `"30min"`, are not supported. - `freq` is not supported: the window features are shifted by `periods` rows. -- `functions` takes `"count"`, `"kurt"`, `"max"`, `"mean"`, `"median"`, `"min"`, - `"skew"`, `"std"`, `"sum"` and `"var"`. +- `functions` takes `"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. - `min_periods` must be greater than 0. - `sort_index` does not apply. @@ -670,6 +673,41 @@ have enough past data to fill the window, contain null values: To take windows with fewer rows at the start of the series, set `min_periods`. +Besides statistics like the mean, we can take the first and last values of each window, +and the rank of the last value within the window: + +.. code:: python + + win_f = WindowFeatures( + variables="irradiation", window=4, functions=["first", "last", "rank"] + ) + + X_tr = win_f.fit_transform(X) + + print(X_tr) + +In the fifth row, the window holds the irradiation of the first 4 rows. Its last value, +0.76, is the third smallest of the window: + +.. code:: text + + shape: (8, 5) + ┌──────────────┬─────────────┬───────────────────────┬──────────────────────┬──────────────────────┐ + │ ambient_temp ┆ irradiation ┆ irradiation_window_4_ ┆ irradiation_window_4 ┆ irradiation_window_4 │ + │ --- ┆ --- ┆ first ┆ _last ┆ _rank │ + │ f64 ┆ f64 ┆ --- ┆ --- ┆ --- │ + │ ┆ ┆ f64 ┆ f64 ┆ f64 │ + ╞══════════════╪═════════════╪═══════════════════════╪══════════════════════╪══════════════════════╡ + │ 31.31 ┆ 0.51 ┆ null ┆ null ┆ null │ + │ 31.51 ┆ 0.79 ┆ null ┆ null ┆ null │ + │ 32.15 ┆ 0.65 ┆ null ┆ null ┆ null │ + │ 32.39 ┆ 0.76 ┆ null ┆ null ┆ null │ + │ 32.62 ┆ 0.42 ┆ 0.51 ┆ 0.76 ┆ 3.0 │ + │ 32.5 ┆ 0.49 ┆ 0.79 ┆ 0.42 ┆ 1.0 │ + │ 32.52 ┆ 0.57 ┆ 0.65 ┆ 0.49 ┆ 2.0 │ + │ 32.68 ┆ 0.56 ┆ 0.76 ┆ 0.57 ┆ 3.0 │ + └──────────────┴─────────────┴───────────────────────┴──────────────────────┴──────────────────────┘ + We can also drop the rows with null values in the window features from the dataframe and the target: diff --git a/feature_engine/timeseries/forecasting/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index 628797144..a7a3de0ef 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -17,8 +17,9 @@ DataFrame = Union[IntoDataFrame, nw.DataFrame] -# pandas' rolling functions that other dataframes support: with narwhals, or with -# polars' own expressions when narwhals has none (they are faster than numpy). +# pandas' rolling functions that other dataframes support: with narwhals, with +# polars' rolling expressions when narwhals has none (they are faster than numpy), +# and with polars aggregations over the rows of each window when polars has none. _NW_ROLLING = { "count": lambda col, win, min_samples: (~col.is_null()) .cast(nw.Float64) @@ -26,6 +27,8 @@ "mean": lambda col, win, min_samples: col.rolling_mean( win, min_samples=min_samples ), + "sem": lambda col, win, min_samples: col.rolling_std(win, min_samples=min_samples) + / (~col.is_null()).cast(nw.Float64).rolling_sum(win, min_samples=1).sqrt(), "std": lambda col, win, min_samples: col.rolling_std(win, min_samples=min_samples), "sum": lambda col, win, min_samples: col.rolling_sum(win, min_samples=min_samples), "var": lambda col, win, min_samples: col.rolling_var(win, min_samples=min_samples), @@ -40,10 +43,19 @@ win, min_samples=min_samples ), "min": lambda col, win, min_samples: col.rolling_min(win, min_samples=min_samples), + "rank": lambda col, win, min_samples: col.rolling_rank( + win, min_samples=min_samples + ), "skew": lambda col, win, min_samples: col.rolling_skew( win, bias=False, min_samples=min_samples ), } +# like pandas, they skip missing values. +_POLARS_ROW_WINDOWS = { + "first": lambda col: col.drop_nulls().first(), + "last": lambda col: col.drop_nulls().last(), + "nunique": lambda col: col.drop_nulls().n_unique(), +} def check_index(X: DataFrame, freq: Any = None) -> None: @@ -223,13 +235,11 @@ def check_window_parameters( f"each window. Got {window} instead." ) function_list = functions if isinstance(functions, list) else [functions] - if not all( - function in _NW_ROLLING or function in _POLARS_ROLLING - for function in function_list - ): + 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"{sorted([*_NW_ROLLING, *_POLARS_ROLLING])}. Got {functions} instead." + f"{supported}. Got {functions} instead." ) if min_periods == 0: raise NotImplementedError( @@ -309,15 +319,27 @@ def add_window_features( if function in _NW_ROLLING: rolled = _NW_ROLLING[function](nw.col(var), win, min_samples) nw_exprs.append(rolled.shift(periods).alias(name)) - else: + elif function in _POLARS_ROLLING: rolled = _POLARS_ROLLING[function](plx.col(var), win, min_samples) native_exprs.append(rolled.shift(periods).alias(name)) + else: + # like pandas, a window needs min_samples values that are not missing. + not_missing = plx.col(var).is_not_null().cast(plx.UInt32) + rolled = plx.when( + not_missing.rolling_sum(win, min_samples=1) >= min_samples + ).then( + _POLARS_ROW_WINDOWS[function](plx.col(var)).rolling( + index_column="__row__", period=f"{win}i" + ) + ) + native_exprs.append(rolled.shift(periods).alias(name)) columns = X.columns X = X.with_columns(nw_exprs) if len(native_exprs) > 0: - # the polars features were added last: restore the order of the names. - X_pl = X.to_native().with_columns(native_exprs) + # the polars features were added last: restore the order of the names, + # which also drops the row numbers that the windows of rows need. + X_pl = X.to_native().with_row_index("__row__").with_columns(native_exprs) X = nw.from_native(X_pl, eager_only=True).select(columns + names) return X diff --git a/feature_engine/timeseries/forecasting/window_features.py b/feature_engine/timeseries/forecasting/window_features.py index 41ab55e2c..f2d2df945 100644 --- a/feature_engine/timeseries/forecasting/window_features.py +++ b/feature_engine/timeseries/forecasting/window_features.py @@ -101,10 +101,15 @@ class WindowFeatures(BaseForecastTransformer): greater than 0. functions: string or list of strings, default = 'mean' - The functions to apply within the window. Valid functions can be found - `here `_. With polars, - the valid functions are 'count', 'kurt', 'max', 'mean', 'median', 'min', - 'skew', 'std', 'sum' and 'var'. + The functions to apply to the values of each variable within the window. + With pandas, the valid functions are the methods of pandas rolling 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 a positive integer. See param `periods` in 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 cd7944201..bc920afc7 100644 --- a/tests/test_time_series/test_forecasting/test_forecasting_helpers.py +++ b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py @@ -109,17 +109,20 @@ def test_add_lag_features_with_fill_value(backend): def test_add_window_features(make_df): X = check_X(make_df({"a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0]})) - names = ["a_max", "a_mean", "b_max", "b_mean"] - Xt = add_window_features(X, ["a", "b"], [2], ["max", "mean"], None, 1, None, names) + names = ["a_max", "a_mean", "a_first", "b_max", "b_mean", "b_first"] + functions = ["max", "mean", "first"] + Xt = add_window_features(X, ["a", "b"], [2], functions, None, 1, None, names) - # max and mean come from different libraries with polars, in the order of names + # with polars, the functions come from different libraries, in the order of names assert frame_to_dict(nw.to_native(Xt, pass_through=True)) == { "a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0], "a_max": [None, None, 2.0, 3.0], "a_mean": [None, None, 1.5, 2.5], + "a_first": [None, None, 1.0, 2.0], "b_max": [None, None, 4.0, 3.0], "b_mean": [None, None, 3.5, 2.5], + "b_first": [None, None, 4.0, 3.0], } diff --git a/tests/test_time_series/test_forecasting/test_window_features.py b/tests/test_time_series/test_forecasting/test_window_features.py index 1cfcfbea2..21d42f6b9 100644 --- a/tests/test_time_series/test_forecasting/test_window_features.py +++ b/tests/test_time_series/test_forecasting/test_window_features.py @@ -14,9 +14,14 @@ "cat": ["a", "b", "c", "d", "e", "f", "g"], } +PANDAS_MAJOR = int(pd.__version__.split(".")[0]) +# pandas < 3 has no rolling first, last and nunique, and its sem divides by n - 1. +PANDAS_3_FUNCTIONS = ["first", "last", "nunique", "sem"] + MSG_POLARS_FUNCTIONS = ( - "With dataframes other than pandas, functions takes only ['count', 'kurt', " - "'max', 'mean', 'median', 'min', 'skew', 'std', 'sum', 'var']. " + "With dataframes other than pandas, functions takes only ['count', 'first', " + "'kurt', 'last', 'max', 'mean', 'median', 'min', 'nunique', 'rank', 'sem', " + "'skew', 'std', 'sum', 'var']. " ) @@ -186,9 +191,16 @@ def test_multiple_windows_and_functions(make_df): ("max", [7.0, 11.0, 16.0]), ("skew", [0.863919, 0.599581, 0.456178]), ("kurt", [-0.285714, -0.768431, -0.951989]), + ("sem", [1.322876, 1.957890, 2.598076]), + ("first", [1.0, 2.0, 4.0]), + ("last", [7.0, 11.0, 16.0]), + ("nunique", [4.0, 4.0, 4.0]), + ("rank", [4.0, 4.0, 4.0]), ], ) 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 = WindowFeatures(variables="x1", window=4, functions=function).fit_transform(X) @@ -199,6 +211,31 @@ def test_functions(make_df, function, expected): ) +@pytest.mark.parametrize( + "function, expected", + [ + ("first", [1.0, 3.0, 3.0]), + ("last", [3.0, 3.0, 3.0]), + ("nunique", [2, 1, 1]), + # the value of the fifth row's window is missing, so it has no rank + ("rank", [2.0, 1.5, None]), + ("sem", [1.0, 0, 0]), + ], +) +def test_functions_skip_missing_values(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({"x1": [1.0, None, 3.0, 3.0, None, 5.0]}) + transformer = WindowFeatures( + window=3, min_periods=2, functions=function, missing_values="ignore" + ) + Xt = transformer.fit_transform(X) + + assert frame_to_dict(Xt)[f"x1_window_3_{function}"] == pytest.approx( + [None, None, None] + expected + ) + + def test_periods(make_df): X = make_df(DATA) Xt = WindowFeatures(window=2, functions="max", periods=3).fit_transform(X) @@ -363,15 +400,6 @@ def test_time_span_windows_with_pandas(df_time, df_time_expected): pd.testing.assert_frame_equal(Xt, expected, check_freq=False) -def test_functions_only_in_pandas(df_time): - transformer = WindowFeatures(variables="irradiation", functions=["sem", "last"]) - Xt = transformer.fit_transform(df_time) - - expected = df_time["irradiation"].rolling(3).agg(["sem", "last"]).shift(1) - expected.columns = ["irradiation_window_3_sem", "irradiation_window_3_last"] - pd.testing.assert_frame_equal(Xt[expected.columns], expected) - - def test_sort_index_with_pandas(df_time): X = df_time.sample(frac=1, random_state=1) @@ -434,7 +462,7 @@ def test_error_if_time_span_window_with_polars(window): WindowFeatures(window=window).fit(pl.DataFrame(DATA)) -@pytest.mark.parametrize("functions", ["sem", ["mean", "last"]]) +@pytest.mark.parametrize("functions", ["quantile", ["mean", "prod"]]) def test_error_if_function_not_supported_with_polars(functions): msg = MSG_POLARS_FUNCTIONS + f"Got {functions} instead." with pytest.raises(NotImplementedError, match=re.escape(msg)): From 6db3d060d58920d7827988d4934d45958e0aad0a Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Thu, 26 Nov 2026 15:46:42 +0100 Subject: [PATCH 6/7] simplify WindowFeatures code and add the tests missing from main check_window_parameters runs its checks in an if block instead of returning early, and transform and _get_new_features_name turn window and functions into lists inline instead of calling _functions_list. Adds the cases main tested that the migrated tests missed: several windows with periods and freq, drop_original with drop_na, the column order with several windows and functions, and input_features as the pandas columns. Co-Authored-By: Claude Opus 5.5 --- .../forecasting/_forecasting_helpers.py | 46 ++++++++-------- .../timeseries/forecasting/window_features.py | 39 +++++--------- .../test_forecasting/test_window_features.py | 52 ++++++++++++++++++- 3 files changed, 87 insertions(+), 50 deletions(-) diff --git a/feature_engine/timeseries/forecasting/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index a7a3de0ef..e3487ea77 100644 --- a/feature_engine/timeseries/forecasting/_forecasting_helpers.py +++ b/feature_engine/timeseries/forecasting/_forecasting_helpers.py @@ -223,30 +223,28 @@ def check_window_parameters( The minimum number of values in a window to return a value. """ # only pandas has an index, and pandas supports every window. - if not isinstance(X, nw.DataFrame): - return - - windows = window if isinstance(window, list) else [window] - if not all(isinstance(win, int) for win in windows): - raise NotImplementedError( - "Time spans in window, like '3D', are only supported with pandas " - "dataframes, because they use the dataframe's DatetimeIndex. With " - "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." - ) - if min_periods == 0: - raise NotImplementedError( - "min_periods=0 is only supported with pandas dataframes. With " - "other dataframes, min_periods takes integers greater than 0 or " - f"None. Got {min_periods} instead." - ) + if isinstance(X, nw.DataFrame): + windows = window if isinstance(window, list) else [window] + if not all(isinstance(win, int) for win in windows): + raise NotImplementedError( + "Time spans in window, like '3D', are only supported with pandas " + "dataframes, because they use the dataframe's DatetimeIndex. With " + "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." + ) + if min_periods == 0: + raise NotImplementedError( + "min_periods=0 is only supported with pandas dataframes. With " + "other dataframes, min_periods takes integers greater than 0 or " + f"None. Got {min_periods} instead." + ) def add_window_features( diff --git a/feature_engine/timeseries/forecasting/window_features.py b/feature_engine/timeseries/forecasting/window_features.py index f2d2df945..ef1a1c015 100644 --- a/feature_engine/timeseries/forecasting/window_features.py +++ b/feature_engine/timeseries/forecasting/window_features.py @@ -307,11 +307,14 @@ def transform(self, X: IntoDataFrame) -> IntoDataFrame: if len(self.variables_) > 0: windows = self.window if isinstance(self.window, list) else [self.window] + functions = ( + self.functions if isinstance(self.functions, list) else [self.functions] + ) X = add_window_features( X, self.variables_, windows, - self._functions_list(), + functions, self.min_periods, self.periods, self.freq, @@ -327,29 +330,15 @@ 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.""" - - functions_ = self._functions_list() - - if isinstance(self.window, list): - feature_names = [ - f"{feature}_window_{win}_{agg}" - for win in self.window - for feature in self.variables_ - for agg in functions_ - ] - else: - feature_names = [ - f"{feature}_window_{self.window}_{agg}" - for feature in self.variables_ - for agg in functions_ - ] - - return feature_names + windows = self.window if isinstance(self.window, list) else [self.window] + functions = ( + self.functions if isinstance(self.functions, list) else [self.functions] + ) + return [ + f"{feature}_window_{win}_{agg}" + for win in windows + for feature in self.variables_ + for agg in functions + ] diff --git a/tests/test_time_series/test_forecasting/test_window_features.py b/tests/test_time_series/test_forecasting/test_window_features.py index 21d42f6b9..07af91e44 100644 --- a/tests/test_time_series/test_forecasting/test_window_features.py +++ b/tests/test_time_series/test_forecasting/test_window_features.py @@ -130,6 +130,8 @@ def test_get_feature_names_out(make_df): ] assert transformer.get_feature_names_out() == expected assert transformer.get_feature_names_out(input_features=original) == expected + # with pandas, the columns are an Index, not a list + assert transformer.get_feature_names_out(input_features=X.columns) == expected transformer = WindowFeatures(window=[2, 3], functions="mean").fit(X) assert transformer.get_feature_names_out() == original + [ @@ -139,6 +141,18 @@ def test_get_feature_names_out(make_df): "x2_window_3_mean", ] + transformer = WindowFeatures(window=[2, 3], functions=["sum", "mean"]).fit(X) + assert transformer.get_feature_names_out() == original + [ + "x1_window_2_sum", + "x1_window_2_mean", + "x2_window_2_sum", + "x2_window_2_mean", + "x1_window_3_sum", + "x1_window_3_mean", + "x2_window_3_sum", + "x2_window_3_mean", + ] + transformer = WindowFeatures(variables="x2", drop_original=True).fit(X) assert transformer.get_feature_names_out() == ["x1", "cat", "x2_window_3_mean"] @@ -160,9 +174,12 @@ def test_error_if_input_features_not_list(make_df): def test_multiple_windows_and_functions(make_df): X = make_df(DATA) - Xt = WindowFeatures(window=[2, 3], functions=["sum", "mean"]).fit_transform(X) + transformer = WindowFeatures(window=[2, 3], functions=["sum", "mean"]) + 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) == { **DATA, "x1_window_2_sum": [None, None, 3.0, 6.0, 11.0, 18.0, 27.0], @@ -333,6 +350,19 @@ def test_drop_na(make_df): } +def test_drop_original_and_drop_na(make_df): + X = make_df(DATA) + transformer = WindowFeatures(window=2, drop_original=True, drop_na=True) + Xt = transformer.fit_transform(X) + + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt) == { + "cat": ["c", "d", "e", "f", "g"], + "x1_window_2_mean": [1.5, 3.0, 5.5, 9.0, 13.5], + "x2_window_2_mean": [15.0, 25.0, 35.0, 45.0, 55.0], + } + + def test_transform_x_y(make_df): X = make_df(DATA) y = make_series(make_df, [1, 2, 3, 4, 5, 6, 7], name="y") @@ -386,6 +416,26 @@ def test_freq_with_pandas(df_time, df_time_expected): pd.testing.assert_frame_equal(Xt, expected, check_freq=False) +def test_multiple_windows_with_periods_and_freq_with_pandas(df_time, df_time_expected): + transformer = WindowFeatures( + variables="irradiation", + window=[2, 3], + functions=["sum", "mean"], + periods=30, + freq="min", + ) + Xt = transformer.fit_transform(df_time).head(8) + + # 30 periods of 1 minute shift the windows by 2 rows, which are 15 minutes apart + expected = df_time_expected.assign( + irradiation_window_2_sum=[np.nan] * 3 + [1.3, 1.44, 1.41, 1.18, 0.91], + irradiation_window_2_mean=[np.nan] * 3 + [0.65, 0.72, 0.705, 0.59, 0.455], + irradiation_window_3_sum=[np.nan] * 4 + [1.95, 2.2, 1.83, 1.67], + irradiation_window_3_mean=[np.nan] * 4 + [0.65, 2.2 / 3, 0.61, 1.67 / 3], + ) + pd.testing.assert_frame_equal(Xt, expected, check_freq=False) + + def test_time_span_windows_with_pandas(df_time, df_time_expected): transformer = WindowFeatures( variables="irradiation", window=["30min", "45min"], functions="max" From bcc2eaf8a63ed69d7554d29c8067833bc9a84d0a Mon Sep 17 00:00:00 2001 From: Soledad Galli Date: Thu, 26 Nov 2026 15:54:07 +0100 Subject: [PATCH 7/7] validate sort_index in WindowFeatures and align the tests with the conventions WindowFeatures now rejects a sort_index that isn't a boolean, as LagFeatures does. The tests check the column order of the window helper, vary every init parameter, check the type of every output and parametrize the duplicated functions error. The polars row-order test is removed, because the base tests cover it. Co-Authored-By: Claude Opus 5.5 --- .../timeseries/forecasting/window_features.py | 5 ++ .../test_forecasting_helpers.py | 3 +- .../test_forecasting/test_window_features.py | 58 +++++++++++-------- 3 files changed, 40 insertions(+), 26 deletions(-) diff --git a/feature_engine/timeseries/forecasting/window_features.py b/feature_engine/timeseries/forecasting/window_features.py index ef1a1c015..1a6cb5295 100644 --- a/feature_engine/timeseries/forecasting/window_features.py +++ b/feature_engine/timeseries/forecasting/window_features.py @@ -259,6 +259,11 @@ def __init__( f"periods must be a positive 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 ) 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 bc920afc7..164eca5dc 100644 --- a/tests/test_time_series/test_forecasting/test_forecasting_helpers.py +++ b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py @@ -114,6 +114,7 @@ def test_add_window_features(make_df): Xt = add_window_features(X, ["a", "b"], [2], functions, None, 1, None, names) # with polars, the functions come from different libraries, in the order of names + assert list(Xt.columns) == ["a", "b"] + names assert frame_to_dict(nw.to_native(Xt, pass_through=True)) == { "a": [1.0, 2.0, 3.0, 4.0], "b": [4.0, 3.0, 2.0, 1.0], @@ -128,7 +129,7 @@ def test_add_window_features(make_df): @pytest.mark.parametrize( "window, functions, min_periods", - [("3D", "mean", None), (3, ["sem"], None), (3, "mean", 0)], + [("3D", "mean", None), (3, ["quantile"], None), (3, "mean", 0)], ) def test_check_window_parameters_accepts_everything_with_pandas( window, functions, min_periods diff --git a/tests/test_time_series/test_forecasting/test_window_features.py b/tests/test_time_series/test_forecasting/test_window_features.py index 07af91e44..659ababc8 100644 --- a/tests/test_time_series/test_forecasting/test_window_features.py +++ b/tests/test_time_series/test_forecasting/test_window_features.py @@ -65,13 +65,11 @@ def test_error_if_functions_not_string_or_list(functions): WindowFeatures(functions=functions) -def test_error_if_functions_duplicated(): - msg = ( - "There are duplicated functions in the list. " - "Got ['sum', 'sum', 'mean'] instead." - ) +@pytest.mark.parametrize("functions", [["sum", "sum", "mean"], ["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)): - WindowFeatures(functions=["sum", "sum", "mean"]) + WindowFeatures(functions=functions) @pytest.mark.parametrize( @@ -83,16 +81,32 @@ def test_error_if_periods_not_positive_integer(periods): WindowFeatures(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)): + WindowFeatures(sort_index=sort_index) + + @pytest.mark.parametrize( - "window, min_periods, functions, periods, freq, sort_index", + "window, min_periods, functions, periods, freq, sort_index, missing_values, " + "drop_original, drop_na", [ - (3, None, "mean", 1, None, True), - ([2, 3], 0, ["sum", "mean", "count"], 2, "15min", False), - (["45min", "30min"], 2, ["std"], 3, "1h", True), + (3, None, "mean", 1, None, True, "raise", False, False), + ([2, 3], 0, ["sum", "mean", "count"], 2, "15min", False, "ignore", True, False), + (["45min", "30min"], 2, ["std"], 3, "1h", True, "ignore", False, True), ], ) def test_init_param_assignment( - window, min_periods, functions, periods, freq, sort_index + window, + min_periods, + functions, + periods, + freq, + sort_index, + missing_values, + drop_original, + drop_na, ): transformer = WindowFeatures( window=window, @@ -101,9 +115,9 @@ def test_init_param_assignment( periods=periods, freq=freq, sort_index=sort_index, - missing_values="ignore", - drop_original=True, - drop_na=True, + missing_values=missing_values, + drop_original=drop_original, + drop_na=drop_na, ) assert transformer.window == window assert transformer.min_periods == min_periods @@ -111,9 +125,9 @@ def test_init_param_assignment( assert transformer.periods == periods assert transformer.freq == freq assert transformer.sort_index == sort_index - assert transformer.missing_values == "ignore" - assert transformer.drop_original is True - assert transformer.drop_na is True + assert transformer.missing_values == missing_values + assert transformer.drop_original == drop_original + assert transformer.drop_na == drop_na # fit and transform @@ -248,6 +262,7 @@ def test_functions_skip_missing_values(make_df, function, expected): ) Xt = transformer.fit_transform(X) + assert isinstance(Xt, make_df) assert frame_to_dict(Xt)[f"x1_window_3_{function}"] == pytest.approx( [None, None, None] + expected ) @@ -492,14 +507,7 @@ def test_integer_column_names_with_pandas(): pd.testing.assert_frame_equal(Xt, expected) -# polars: the rows are used in the order given and the windows are numbers of rows -def test_rows_keep_their_order_with_polars(): - X = pl.DataFrame({"x1": [4.0, 1.0, 7.0, 2.0]}) - Xt = WindowFeatures(window=2, functions="max").fit_transform(X) - - assert frame_to_dict(Xt)["x1_window_2_max"] == [None, None, 4.0, 7.0] - - +# polars: the windows are numbers of rows, and min_periods must be greater than 0 @pytest.mark.parametrize("window", ["3D", ["45min", "30min"], [2, "30min"]]) def test_error_if_time_span_window_with_polars(window): msg = (