diff --git a/docs/user_guide/timeseries/forecasting/WindowFeatures.rst b/docs/user_guide/timeseries/forecasting/WindowFeatures.rst index f601afcb6..69cdf362a 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,16 +72,17 @@ 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 -by pandas. For supported aggregation functions, see Rolling Window +:class:`WindowFeatures` performs the mathematical operations over the windows with the +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 @@ -94,8 +95,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 +507,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 +607,126 @@ 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"`, `"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. + +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:: text + + 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`. + +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: + +.. 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/_forecasting_helpers.py b/feature_engine/timeseries/forecasting/_forecasting_helpers.py index 006640a1b..e3487ea77 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,46 @@ DataFrame = Union[IntoDataFrame, nw.DataFrame] +# 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) + .rolling_sum(win, min_samples=min_samples), + "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), +} +_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), + "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: """ @@ -155,3 +196,148 @@ 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 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( + 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. + 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)) + 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, + # 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 f5f73c7f7..1a6cb5295 100644 --- a/feature_engine/timeseries/forecasting/window_features.py +++ b/feature_engine/timeseries/forecasting/window_features.py @@ -1,6 +1,7 @@ -from typing import Callable, List, Union +from typing import Callable, List, Optional, Union -import pandas as pd +import narwhals as nw +from narwhals.typing import IntoDataFrame, IntoSeries from feature_engine._docstrings.fit_attributes import ( _feature_names_in_docstring, @@ -17,6 +18,16 @@ _fit_transform_docstring, ) from feature_engine._docstrings.substitute import Substitution +from feature_engine.dataframe_checks import check_X +from feature_engine.dataframe_helpers import ( + drop_variables_from_df, + filter_rows, + rows_with_missing_values, +) +from feature_engine.timeseries.forecasting._forecasting_helpers import ( + add_window_features, + check_window_parameters, +) from feature_engine.timeseries.forecasting.base_forecast_transformers import ( BaseForecastTransformer, ) @@ -41,11 +52,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 +65,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 +92,36 @@ 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 `_. - - periods: int, list of ints, default=1 + 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 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 +178,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__( @@ -170,24 +214,56 @@ 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 min_periods is not None and ( + not isinstance(min_periods, int) + or isinstance(min_periods, bool) + or min_periods < 0 + ): + raise ValueError( + "min_periods must be None or a non-negative integer. " + f"Got {min_periods} instead." + ) - if not isinstance(functions, (str, list)) or not all( - isinstance(val, str) for val in functions + if ( + not isinstance(functions, (str, list)) + or len(functions) == 0 + or not all(isinstance(val, str) for val in functions) ): raise ValueError( - f"functions must be a string or a list of strings. " + "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." ) + 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 ) @@ -199,75 +275,75 @@ def __init__( self.freq = freq self.sort_index = sort_index - def transform(self, X: pd.DataFrame) -> pd.DataFrame: + def fit(self, X: IntoDataFrame, y: Optional[IntoSeries] = None): + """ + This transformer does not learn parameters. + + Parameters + ---------- + X: dataframe of shape = [n_samples, n_features] + The training dataset. + + y: Series, default=None + y is not needed in this transformer. You can pass None or y. + """ + super().fit(X, y) + check_window_parameters( + check_X(X), self.window, self.functions, self.min_periods + ) + 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) + 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, + functions, + self.min_periods, + self.periods, + self.freq, + self._get_new_features_name(), ) - tmp.columns = self._get_new_features_name() - - X = X.merge(tmp, left_index=True, right_index=True, how="left") - - if self.drop_original: - X = X.drop(self.variables_, axis=1) + if self.drop_original is True: + X = drop_variables_from_df(X, self.variables_) - if self.drop_na: - X = X.dropna(subset=tmp.columns, axis=0) + if self.drop_na is True: + new_features = self._get_new_features_name() + X = filter_rows(X, ~rows_with_missing_values(X, new_features)) - return X + return nw.to_native(X, pass_through=True) def _get_new_features_name(self) -> List: - """Get names of the lag features.""" - - if not isinstance(self.functions, list): - functions_ = [self.functions] - else: - functions_ = self.functions - - 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 + """Get names of the window features.""" + 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_forecasting_helpers.py b/tests/test_time_series/test_forecasting/test_forecasting_helpers.py index c274554ce..164eca5dc 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,34 @@ 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", "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) + + # 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], + "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], + } + + +@pytest.mark.parametrize( + "window, functions, min_periods", + [("3D", "mean", None), (3, ["quantile"], 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 1ec83ed8e..659ababc8 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,537 @@ +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 - -_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"), -] +from tests.backend_helpers import frame_to_dict, make_series + +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"], +} + +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', 'first', " + "'kurt', 'last', 'max', 'mean', 'median', 'min', 'nunique', 'rank', 'sem', " + "'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", [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("_periods", [1, 2, 3]) -def test_permitted_param_periods(_periods): - transformer = WindowFeatures(periods=_periods) - assert transformer.periods == _periods +@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. Got {window} instead." + with pytest.raises(ValueError, match=re.escape(msg)): + WindowFeatures(window=window) -@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) +@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", ["mean", "std", ["sum", "mean"], ["sum", "mean", "count"]] + "functions", [3.33, [1, "mean"], None, ("mean", "sum"), [], ""] ) -def test_permitted_param_functions(_functions): - transformer = WindowFeatures(functions=_functions) - assert transformer.functions == _functions +def test_error_if_functions_not_string_or_list(functions): + msg = ( + "functions must be a string or a non-empty list of strings. " + f"Got {functions} instead." + ) + with pytest.raises(ValueError, match=re.escape(msg)): + WindowFeatures(functions=functions) + + +@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=functions) @pytest.mark.parametrize( - "_functions", [3.33, [1, "mean"], None, ["sum", "sum", "mean"]] + "periods", ["pizza", 3.33, ["mate", "cumbia"], None, 0, -1, True] ) -def test_error_when_non_permitted_param_functions(_functions): - with pytest.raises(ValueError): - WindowFeatures(functions=_functions) - +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("_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) +@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("_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( + "window, min_periods, functions, periods, freq, sort_index, missing_values, " + "drop_original, drop_na", + [ + (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, + missing_values, + drop_original, + drop_na, +): + transformer = WindowFeatures( + window=window, + min_periods=min_periods, + functions=functions, + periods=periods, + freq=freq, + sort_index=sort_index, + missing_values=missing_values, + drop_original=drop_original, + drop_na=drop_na, + ) + assert transformer.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 == missing_values + assert transformer.drop_original == drop_original + assert transformer.drop_na == drop_na + + +# 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 + # 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 + [ + "x1_window_2_mean", + "x2_window_2_mean", + "x1_window_3_mean", + "x2_window_3_mean", + ] -def test_get_feature_names_out(df_time): - # input features - original_features = ["ambient_temp", "module_temp", "irradiation", "color"] + 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", + ] - # case 1: 1 window, multiple variables, multiple functions - tr = WindowFeatures(window=3, functions=["mean", "sum"]) - tr.fit(df_time) + 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) + 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], + "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], + } - # 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 - with pytest.raises(ValueError): - # get error when a user passes a string instead of list - tr.get_feature_names_out(input_features=["ambient_temp"]) +@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]), + ("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) + + 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 + ) - with pytest.raises(ValueError): - # assert error when uses passes features that were not transformed - tr.get_feature_names_out(input_features=["color"]) - # case 2: 1 window, 1 variable, multiple functions - tr = WindowFeatures( - variables="ambient_temp", window=2, functions=["sum", "mean", "count"] +@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" ) - tr.fit(df_time) + Xt = transformer.fit_transform(X) - # 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 + assert isinstance(Xt, make_df) + assert frame_to_dict(Xt)[f"x1_window_3_{function}"] == pytest.approx( + [None, None, None] + expected ) -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, - ], +def test_periods(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=2, functions="max", periods=3).fit_transform(X) + + 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], } - 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) +def test_min_periods(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=3, min_periods=1).fit_transform(X) - # Case 2: when drop_original is true - transformer = WindowFeatures( - window=3, functions=["median"], periods=2, drop_original=True - ) - df_tr = transformer.fit_transform(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], + } - assert df_tr.head(9).equals( - expected_results_df.drop(["ambient_temp", "module_temp", "irradiation"], axis=1) - ) - # 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) +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) + + 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], + } - assert df_tr.head(9).equals( - expected_results_df.drop(["ambient_temp_window_3_median"], axis=1) - ) - # Case 4: user indicates 1 variable +@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( - variables=["module_temp"], window=3, functions=["median"], periods=2 + variables="x1", + functions=["mean", "count"], + min_periods=min_periods, + missing_values="ignore", ) - transformer.fit(df_time) - df_tr = transformer.transform(df_time) + Xt = transformer.fit_transform(X) + + 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 - assert df_tr.head(9).equals( - expected_results_df.drop( - ["ambient_temp_window_3_median", "irradiation_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) -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) == { + "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], } - 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_drop_na(make_df): + X = make_df(DATA) + Xt = WindowFeatures(window=[2, 4], functions="min", drop_na=True).fit_transform(X) + + 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], + } - assert df_tr.head(9).round(3).equals(expected_results_df) - # Case 2: when drop_original is true +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") + 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] + + +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) - - assert ( - df_tr.head(9) - .round(3) - .equals(expected_results_df.drop(["module_temp_window_2_sum"], axis=1)) - ) + Xt = transformer.fit_transform(df_time).head(8) - # 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 - ) - ) + 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) -def test_multiple_windows(df_time): - - # Case 1: automatically select variables +def test_multiple_windows_with_periods_and_freq_with_pandas(df_time, df_time_expected): transformer = WindowFeatures( - window=[2, 3], functions=["sum", "mean"], periods=15, freq="min" - ) - 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"], + variables="irradiation", window=[2, 3], functions=["sum", "mean"], - freq="30min", + periods=30, + freq="min", ) - 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") + 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], ) - 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() + pd.testing.assert_frame_equal(Xt, expected, check_freq=False) - assert df_time_tr.equals(X_tr) - # Case 4: user indicates 1 variable +def test_time_span_windows_with_pandas(df_time, df_time_expected): transformer = WindowFeatures( - variables=["irradiation"], - window=[2, 3], - functions="std", - periods=1, + variables="irradiation", window=["30min", "45min"], functions="max" ) - 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) - + Xt = transformer.fit_transform(df_time).head(8) -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"] - - transformer = WindowFeatures(window=3, min_periods=1) - df_tr = transformer.fit_transform(df_time) - - expected = ( - df_time[variables].rolling(window=3, min_periods=1).agg("mean").shift(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], ) - expected.columns = [f"{var}_window_3_mean" for var in variables] - - assert_frame_equal(df_tr[expected.columns], expected) - - # with min_periods=1 only the very first row (shifted out) remains NaN - assert df_tr["ambient_temp_window_3_mean"].isna().sum() == 1 - - # 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 - + pd.testing.assert_frame_equal(Xt, expected, check_freq=False) -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) - 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"), - ) +def test_sort_index_with_pandas(df_time): + X = df_time.sample(frac=1, random_state=1) - -def test_sort_index(df_time): - # Shuffle dataframe - Xs = df_time.copy() - Xs = Xs.sample(frac=1) + Xt = WindowFeatures(sort_index=True).fit_transform(X) + pd.testing.assert_frame_equal(Xt, WindowFeatures().fit_transform(df_time)) transformer = WindowFeatures(sort_index=False) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal(df_tr[transformer.variables_], Xs[transformer.variables_]) + Xt = transformer.fit_transform(X) + pd.testing.assert_frame_equal(Xt[df_time.columns], X) - transformer = WindowFeatures(sort_index=True) - df_tr = transformer.fit_transform(Xs) - assert_frame_equal( - df_tr[transformer.variables_], Xs[transformer.variables_].sort_index() - ) +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) -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:]) - - # Case 1: automatically select variables - transformer = WindowFeatures( - window=3, functions=["median"], periods=2, drop_na=True - ) - df_tr = transformer.fit_transform(df) + Xt, yt = transformer.transform_x_y(X, y) - assert df_tr.equals(expected_results_df) + pd.testing.assert_frame_equal(Xt, transformer.transform(X)) + pd.testing.assert_series_equal(yt, y.loc[Xt.index]) - # 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) - ) +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) - # Case 3: user indicates multiple variables - transformer = WindowFeatures( - variables=["module_temp", "irradiation"], - window=3, - functions="median", - periods=2, - drop_na=True, + 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], ) - transformer.fit(df) - df_tr = transformer.transform(df) - - assert df_tr.equals( - expected_results_df.drop(["ambient_temp_window_3_median"], axis=1) + # the columns started as a mix of integers and strings + expected.columns = expected.columns.astype(object) + pd.testing.assert_frame_equal(Xt, expected) + + +# polars: the 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 = ( + "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)) -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 - ) +@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)): + WindowFeatures(functions=functions).fit(pl.DataFrame(DATA)) - df_tr = transformer.fit_transform(df) - assert df_tr.equals(expected_results_df) - assert len(df_tr) != len(y) - - Xt, yt = transformer.transform_x_y(df, y) - assert len(Xt) == len(yt) - assert len(y) != len(yt) - assert (Xt.index == yt.index).all() +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))