diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 3a67e848024ac..2a0e9f44740bb 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -994,6 +994,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrameGroupBy.__getitem__` with non-unique columns incorrectly returning a malformed :class:`SeriesGroupBy` instead of :class:`DataFrameGroupBy` (:issue:`41427`) - Bug in :meth:`DataFrameGroupBy.transform` with non-unique columns incorrectly raising ``AttributeError`` (:issue:`41427`) - Bug in :meth:`Resampler.apply` with non-unique columns incorrectly dropping duplicated columns (:issue:`41445`) +- Bug in :meth:`DataFrame.rolling.__iter__` where ``on`` was not assigned to the index of the resulting objects (:issue:`40373`) - Bug in :meth:`DataFrameGroupBy.transform` and :meth:`DataFrameGroupBy.agg` with ``engine="numba"`` where ``*args`` were being cached with the user passed function (:issue:`41647`) Reshaping diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 0ef0896df8d44..dfb74b38cd9cf 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -291,6 +291,7 @@ def __repr__(self) -> str: def __iter__(self): obj = self._create_data(self._selected_obj) + obj = obj.set_axis(self._on) indexer = self._get_window_indexer() start, end = indexer.get_window_bounds( diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 4846e15da039f..7a3e1e002759d 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -742,7 +742,7 @@ def test_iter_rolling_dataframe(df, expected, window, min_periods): ], ) def test_iter_rolling_on_dataframe(expected, window): - # GH 11704 + # GH 11704, 40373 df = DataFrame( { "A": [1, 2, 3, 4, 5], @@ -751,7 +751,9 @@ def test_iter_rolling_on_dataframe(expected, window): } ) - expected = [DataFrame(values, index=index) for (values, index) in expected] + expected = [ + DataFrame(values, index=df.loc[index, "C"]) for (values, index) in expected + ] for (expected, actual) in zip(expected, df.rolling(window, on="C")): tm.assert_frame_equal(actual, expected)