Skip to content

BUG: Fix .rolling().mean() reassignment returning NaNs (pandas-dev#61841) #61851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

abujabarmubarak
Copy link

This pull request resolves a bug highlighted in issue [#61841](#61841), where reassigning the result of .rolling().mean() to the same column in a DataFrame results in all-NaN values after the first assignment.

🔜 Root Cause:

The root cause was improper alignment when using the step parameter within the Window._apply() function. The rolling results were sliced using self.step before being fully aligned with the original index, which caused mismatches in the returned Series/DataFrame.

🔧 Fix Implemented:

  • Adjusted the logic in Window._apply() to apply self.step only after the result is completely constructed and aligned.
  • Moved Series and DataFrame imports from inside a type-checking block (if TYPE_CHECKING) to the top of the file. This eliminates pre-commit CI errors related to inconsistent namespace usage.

📄 Verification:

The fix was verified by executing:

import pandas as pd
import numpy as np

df = pd.DataFrame({"Close": np.arange(1, 31)})
df = df.copy()
df["SMA20"] = df["Close"].rolling(20).mean()
df["SMA20"] = df["Close"].rolling(20).mean()
print(df.tail())

This now works as expected, and outputs the correct rolling mean values.

All relevant pre-commit hooks and CI checks pass after the changes.


Thank you for reviewing this fix!

…nt imports (pandas-dev#61841)

This commit addresses a bug (issue pandas-dev#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant