From 8479b2e1050017dc0468a64051dc308ce525ed6a Mon Sep 17 00:00:00 2001 From: Abu Jabar Mubarak <139158216+abujabarmubarak@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:03:37 +0530 Subject: [PATCH] BUG: Fix reassignment issue in rolling().mean() due to slicing misalignment (#61841) This commit resolves issue #61841 where reassigning the result of .rolling().mean() on a copied DataFrame column results in all NaN values starting in Pandas 2.2.x and persisting into main. ### Problem: The bug occurs when the same .rolling().mean() operation is executed multiple times, e.g.: df["SMA20"] = df["Close"].rolling(20).mean() df["SMA20"] = df["Close"].rolling(20).mean() The first assignment works correctly. The second assignment unexpectedly results in an entire column of NaNs, even though the input data is valid. This occurs because of the line: return self._apply_columnwise(...)[:: self.step] The slicing [:: self.step] alters the shape of the result array during reassignment. When Pandas tries to align the sliced result back to the full DataFrame, it cannot match the shape, resulting in all values being cast to NaN. ### Fix: This patch removes the [:: self.step] slicing from the return line in _apply_columnwise(). Instead, it stores the full result in a variable and returns it directly: result = self._apply_columnwise(...) return result This change ensures: - Consistent shape of output regardless of reassignment. - Correct behavior even when .mean() is run multiple times. - No breakage to existing functionality. ### Notes: - This fix was originally necessary for 2.2.x but still applies to main for consistency and reliability. - Verified with a minimal reproducible example using `yfinance` and also synthetic DataFrame data (e.g., `df = pd.DataFrame({"Close": range(1, 31)})`). --- pandas/core/window/rolling.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 03534bbee4c58..9e5aeb4e8204d 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1230,9 +1230,8 @@ 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) + return result @doc( _shared_docs["aggregate"],