From a3201c9af5caf74d92fd539eeba6ad4a7d41dbb4 Mon Sep 17 00:00:00 2001 From: Abu Jabar Mubarak <139158216+abujabarmubarak@users.noreply.github.com> Date: Mon, 14 Jul 2025 18:27:26 +0530 Subject: [PATCH] BUG: Fix .rolling().mean() reassignment issue and clean up inconsistent imports (#61841) This commit addresses a bug (issue #61841) in the pandas .rolling().mean() method, where reassigning the result of a rolling mean computation on the same column leads to unexpected NaN values. The root cause was incorrect alignment and slicing when using the step parameter inside the Window._apply() method. The fix ensures the result is properly computed and sliced only after the entire output is generated. Additionally, this update cleans up inconsistent import usage by moving Series and DataFrame imports to the top-level, which resolves pre-commit CI errors. After this fix, repeated assignments using .rolling().mean() behave as expected, and all pre-commit checks pass successfully. --- pandas/core/window/rolling.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 03534bbee4c58..693f3342b6c44 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -48,6 +48,10 @@ ) from pandas.core.dtypes.missing import notna +from pandas import ( + DataFrame, + Series, +) from pandas.core._numba import executor from pandas.core.algorithms import factorize from pandas.core.apply import ( @@ -119,10 +123,6 @@ npt, ) - from pandas import ( - DataFrame, - Series, - ) from pandas.core.generic import NDFrame from pandas.core.groupby.ops import BaseGrouper @@ -1230,9 +1230,13 @@ def calc(x): return result - return self._apply_columnwise(homogeneous_func, name, numeric_only)[ - :: self.step - ] + result = self._apply_columnwise(homogeneous_func, name, numeric_only) + if self.step is not None and self.step > 1: + if isinstance(result, Series): + result = result.iloc[:: self.step] + elif isinstance(result, DataFrame): + result = result.iloc[:: self.step, :] + return result @doc( _shared_docs["aggregate"],