| 1 | FeatureUnion not working when aggregating data and pandas transform output selected |
| 2 | ### Describe the bug |
| 3 | |
| 4 | I would like to use `pandas` transform output and use a custom transformer in a feature union which aggregates data. When I'm using this combination I got an error. When I use default `numpy` output it works fine. |
| 5 | |
| 6 | ### Steps/Code to Reproduce |
| 7 | |
| 8 | ```python |
| 9 | import pandas as pd |
| 10 | from sklearn.base import BaseEstimator, TransformerMixin |
| 11 | from sklearn import set_config |
| 12 | from sklearn.pipeline import make_union |
| 13 | |
| 14 | index = pd.date_range(start="2020-01-01", end="2020-01-05", inclusive="left", freq="H") |
| 15 | data = pd.DataFrame(index=index, data=[10] * len(index), columns=["value"]) |
| 16 | data["date"] = index.date |
| 17 | |
| 18 | |
| 19 | class MyTransformer(BaseEstimator, TransformerMixin): |
| 20 | def fit(self, X: pd.DataFrame, y: pd.Series | None = None, **kwargs): |
| 21 | return self |
| 22 | |
| 23 | def transform(self, X: pd.DataFrame, y: pd.Series | None = None) -> pd.DataFrame: |
| 24 | return X["value"].groupby(X["date"]).sum() |
| 25 | |
| 26 | |
| 27 | # This works. |
| 28 | set_config(transform_output="default") |
| 29 | print(make_union(MyTransformer()).fit_transform(data)) |
| 30 | |
| 31 | # This does not work. |
| 32 | set_config(transform_output="pandas") |
| 33 | print(make_union(MyTransformer()).fit_transform(data)) |
| 34 | ``` |
| 35 | |
| 36 | ### Expected Results |
| 37 | |
| 38 | No error is thrown when using `pandas` transform output. |
| 39 | |
| 40 | ### Actual Results |
| 41 | |
| 42 | ```python |
| 43 | --------------------------------------------------------------------------- |
| 44 | ValueError Traceback (most recent call last) |
| 45 | Cell In[5], line 25 |
| 46 | 23 # This does not work. |
| 47 | 24 set_config(transform_output="pandas") |
| 48 | ---> 25 print(make_union(MyTransformer()).fit_transform(data)) |
| 49 | |
| 50 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/sklearn/utils/_set_output.py:150, in _wrap_method_output.<locals>.wrapped(self, X, *args, **kwargs) |
| 51 | 143 if isinstance(data_to_wrap, tuple): |
| 52 | 144 # only wrap the first output for cross decomposition |
| 53 | 145 return ( |
| 54 | 146 _wrap_data_with_container(method, data_to_wrap[0], X, self), |
| 55 | 147 *data_to_wrap[1:], |
| 56 | 148 ) |
| 57 | --> 150 return _wrap_data_with_container(method, data_to_wrap, X, self) |
| 58 | |
| 59 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/sklearn/utils/_set_output.py:130, in _wrap_data_with_container(method, data_to_wrap, original_input, estimator) |
| 60 | 127 return data_to_wrap |
| 61 | 129 # dense_config == "pandas" |
| 62 | --> 130 return _wrap_in_pandas_container( |
| 63 | 131 data_to_wrap=data_to_wrap, |
| 64 | 132 index=getattr(original_input, "index", None), |
| 65 | 133 columns=estimator.get_feature_names_out, |
| 66 | 134 ) |
| 67 | |
| 68 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/sklearn/utils/_set_output.py:59, in _wrap_in_pandas_container(data_to_wrap, columns, index) |
| 69 | 57 data_to_wrap.columns = columns |
| 70 | 58 if index is not None: |
| 71 | ---> 59 data_to_wrap.index = index |
| 72 | 60 return data_to_wrap |
| 73 | 62 return pd.DataFrame(data_to_wrap, index=index, columns=columns) |
| 74 | |
| 75 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/pandas/core/generic.py:5588, in NDFrame.__setattr__(self, name, value) |
| 76 | 5586 try: |
| 77 | 5587 object.__getattribute__(self, name) |
| 78 | -> 5588 return object.__setattr__(self, name, value) |
| 79 | 5589 except AttributeError: |
| 80 | 5590 pass |
| 81 | |
| 82 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/pandas/_libs/properties.pyx:70, in pandas._libs.properties.AxisProperty.__set__() |
| 83 | |
| 84 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/pandas/core/generic.py:769, in NDFrame._set_axis(self, axis, labels) |
| 85 | 767 def _set_axis(self, axis: int, labels: Index) -> None: |
| 86 | 768 labels = ensure_index(labels) |
| 87 | --> 769 self._mgr.set_axis(axis, labels) |
| 88 | 770 self._clear_item_cache() |
| 89 | |
| 90 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/pandas/core/internals/managers.py:214, in BaseBlockManager.set_axis(self, axis, new_labels) |
| 91 | 212 def set_axis(self, axis: int, new_labels: Index) -> None: |
| 92 | 213 # Caller is responsible for ensuring we have an Index object. |
| 93 | --> 214 self._validate_set_axis(axis, new_labels) |
| 94 | 215 self.axes[axis] = new_labels |
| 95 | |
| 96 | File ~/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/pandas/core/internals/base.py:69, in DataManager._validate_set_axis(self, axis, new_labels) |
| 97 | 66 pass |
| 98 | 68 elif new_len != old_len: |
| 99 | ---> 69 raise ValueError( |
| 100 | 70 f"Length mismatch: Expected axis has {old_len} elements, new " |
| 101 | 71 f"values have {new_len} elements" |
| 102 | 72 ) |
| 103 | |
| 104 | ValueError: Length mismatch: Expected axis has 4 elements, new values have 96 elements |
| 105 | ``` |
| 106 | |
| 107 | ### Versions |
| 108 | |
| 109 | ```shell |
| 110 | System: |
| 111 | python: 3.10.6 (main, Aug 30 2022, 05:11:14) [Clang 13.0.0 (clang-1300.0.29.30)] |
| 112 | executable: /Users/macbookpro/.local/share/virtualenvs/3e_VBrf2/bin/python |
| 113 | machine: macOS-11.3-x86_64-i386-64bit |
| 114 | |
| 115 | Python dependencies: |
| 116 | sklearn: 1.2.1 |
| 117 | pip: 22.3.1 |
| 118 | setuptools: 67.3.2 |
| 119 | numpy: 1.23.5 |
| 120 | scipy: 1.10.1 |
| 121 | Cython: None |
| 122 | pandas: 1.4.4 |
| 123 | matplotlib: 3.7.0 |
| 124 | joblib: 1.2.0 |
| 125 | threadpoolctl: 3.1.0 |
| 126 | |
| 127 | Built with OpenMP: True |
| 128 | |
| 129 | threadpoolctl info: |
| 130 | user_api: blas |
| 131 | internal_api: openblas |
| 132 | prefix: libopenblas |
| 133 | filepath: /Users/macbookpro/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/numpy/.dylibs/libopenblas64_.0.dylib |
| 134 | version: 0.3.20 |
| 135 | threading_layer: pthreads |
| 136 | architecture: Haswell |
| 137 | num_threads: 4 |
| 138 | |
| 139 | user_api: openmp |
| 140 | internal_api: openmp |
| 141 | prefix: libomp |
| 142 | filepath: /Users/macbookpro/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/sklearn/.dylibs/libomp.dylib |
| 143 | version: None |
| 144 | num_threads: 8 |
| 145 | |
| 146 | user_api: blas |
| 147 | internal_api: openblas |
| 148 | prefix: libopenblas |
| 149 | filepath: /Users/macbookpro/.local/share/virtualenvs/3e_VBrf2/lib/python3.10/site-packages/scipy/.dylibs/libopenblas.0.dylib |
| 150 | version: 0.3.18 |
| 151 | threading_layer: pthreads |
| 152 | architecture: Haswell |
| 153 | num_threads: 4 |
| 154 | ``` |
| 155 | |