diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 990962673b8..5c0d3c3c843 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -42,6 +42,8 @@ Performance Bug fixes ~~~~~~~~~ +- Fix bug where weighted ``polyfit`` were changing the original object (:issue:`5644`, :pull:`7900`). + By `Mattia Almansi `_. - Don't call ``CachingFileManager.__del__`` on interpreter shutdown (:issue:`7814`, :pull:`7880`). By `Justus Magin `_. diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 81860bede95..0f271e9d7e4 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -7972,7 +7972,7 @@ def polyfit( scale_da = scale if w is not None: - rhs *= w[:, np.newaxis] + rhs = rhs * w[:, np.newaxis] with warnings.catch_warnings(): if full: # Copy np.polyfit behavior diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index cc9220dfe33..01c26ad6104 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -6217,6 +6217,14 @@ def test_polyfit_output(self) -> None: out = ds.polyfit("time", 2) assert len(out.data_vars) == 0 + def test_polyfit_weighted(self) -> None: + # Make sure weighted polyfit does not change the original object (issue #5644) + ds = create_test_data(seed=1) + ds_copy = ds.copy(deep=True) + + ds.polyfit("dim2", 2, w=np.arange(ds.sizes["dim2"])) + xr.testing.assert_identical(ds, ds_copy) + def test_polyfit_warnings(self) -> None: ds = create_test_data(seed=1)