From 3da3d5ab5976bdcde52b7866cf08bd3f0159768c Mon Sep 17 00:00:00 2001 From: Abu Jabar Mubarak <139158216+abujabarmubarak@users.noreply.github.com> Date: Mon, 14 Jul 2025 11:34:54 +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 | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 03534bbee4c58..bc732c48f9318 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -48,6 +48,11 @@ ) 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 +124,7 @@ npt, ) - from pandas import ( - DataFrame, - Series, - ) + from pandas.core.generic import NDFrame from pandas.core.groupby.ops import BaseGrouper @@ -1230,9 +1232,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"],