From a96cd884f261595933cd432a6619f47617a861ea Mon Sep 17 00:00:00 2001 From: MeeseeksMachine <39504233+meeseeksmachine@users.noreply.github.com> Date: Thu, 22 Jul 2021 18:02:45 -0700 Subject: [PATCH] Backport PR #42633: Fixed regression for SettingWithCopyWarning showing incorrect stacklevel (#42678) Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com> --- doc/source/whatsnew/v1.3.1.rst | 1 + pandas/core/frame.py | 2 +- pandas/tests/indexing/test_chaining_and_caching.py | 10 ++++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.3.1.rst b/doc/source/whatsnew/v1.3.1.rst index b6fdbec68d776..b5f4b5f5375e8 100644 --- a/doc/source/whatsnew/v1.3.1.rst +++ b/doc/source/whatsnew/v1.3.1.rst @@ -25,6 +25,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.isin` and :meth:`Series.isin` raising ``TypeError`` with nullable data containing at least one missing value (:issue:`42405`) - Regression in :func:`concat` between objects with bool dtype and integer dtype casting to object instead of to integer (:issue:`42092`) - Bug in :class:`Series` constructor not accepting a ``dask.Array`` (:issue:`38645`) +- Fixed regression for ``SettingWithCopyWarning`` displaying incorrect stacklevel (:issue:`42570`) - Fixed regression in :func:`to_datetime` returning pd.NaT for inputs that produce duplicated values, when ``cache=True`` (:issue:`42259`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ccea94228c563..21e90e5bc507d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3754,7 +3754,7 @@ def _set_item_mgr(self, key, value: ArrayLike) -> None: # try to set first as we want an invalid # value exception to occur first if len(self): - self._check_setitem_copy() + self._check_setitem_copy(stacklevel=5) def _iset_item(self, loc: int, value) -> None: arraylike = self._sanitize_column(value) diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index a38c652953fab..90bda69eaf139 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -435,6 +435,16 @@ def test_detect_chained_assignment_warnings_filter_and_dupe_cols(self): ) tm.assert_frame_equal(df, expected) + @pytest.mark.parametrize("rhs", [3, DataFrame({0: [1, 2, 3, 4]})]) + def test_detect_chained_assignment_warning_stacklevel(self, rhs): + # GH#42570 + df = DataFrame(np.arange(25).reshape(5, 5)) + chained = df.loc[:3] + with option_context("chained_assignment", "warn"): + with tm.assert_produces_warning(com.SettingWithCopyWarning) as t: + chained[2] = rhs + assert t[0].filename == __file__ + # TODO(ArrayManager) fast_xs with array-like scalars is not yet working @td.skip_array_manager_not_yet_implemented def test_chained_getitem_with_lists(self):