From 8ac6cc708e0ea41a12feb1e484696e14a030ec76 Mon Sep 17 00:00:00 2001 From: Matthew Roeschke Date: Sun, 9 May 2021 20:49:08 -0700 Subject: [PATCH] BUG: Rolling.__iter__ includes on index columns in the result --- doc/source/whatsnew/v1.3.0.rst | 1 + pandas/core/window/rolling.py | 1 + pandas/tests/window/test_rolling.py | 6 ++++-- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index cf3dd1b0e3226..826676622d4eb 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -892,6 +892,7 @@ Groupby/resample/rolling - Bug in :meth:`SeriesGroupBy.agg` failing to retain ordered :class:`CategoricalDtype` on order-preserving aggregations (:issue:`41147`) - Bug in :meth:`DataFrameGroupBy.min` and :meth:`DataFrameGroupBy.max` with multiple object-dtype columns and ``numeric_only=False`` incorrectly raising ``ValueError`` (:issue:41111`) - Bug in :meth:`DataFrameGroupBy.rank` with the GroupBy object's ``axis=0`` and the ``rank`` method's keyword ``axis=1`` (:issue:`41320`) +- Bug in :meth:`DataFrame.rolling.__iter__` where ``on`` was not assigned to the index of the resulting objects (:issue:`40373`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index b51875134c614..81db0bf6a9a90 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -279,6 +279,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 28465e3a979a7..6690065e22fb4 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -744,7 +744,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], @@ -753,7 +753,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)