diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index d283d4450e6bf..7cb7db27ae603 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -364,6 +364,7 @@ Indexing - Bug in :class:`Index` constructor where an unhelpful error message was raised for ``numpy`` scalars (:issue:`33017`) - Bug in :meth:`DataFrame.lookup` incorrectly raising an ``AttributeError`` when ``frame.index`` or ``frame.columns`` is not unique; this will now raise a ``ValueError`` with a helpful error message (:issue:`33041`) - Bug in :meth:`DataFrame.iloc.__setitem__` creating a new array instead of overwriting ``Categorical`` values in-place (:issue:`32831`) +- Bug in :meth:`DataFrame.copy` _item_cache not invalidated after copy causes post-copy value updates to not be reflected (:issue:`31784`) Missing ^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9640c1e087f47..82cc45ee16c00 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5665,6 +5665,7 @@ def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: dtype: object """ data = self._data.copy(deep=deep) + self._clear_item_cache() return self._constructor(data).__finalize__(self) def __copy__(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 91627b46c2fee..4149485be181d 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -540,3 +540,21 @@ def test_attrs(self): result = df.rename(columns=str) assert result.attrs == {"version": 1} + + def test_cache_on_copy(self): + # GH 31784 _item_cache not cleared on copy causes incorrect reads after updates + df = DataFrame({"a": [1]}) + + df["x"] = [0] + df["a"] + + df.copy() + + df["a"].values[0] = -1 + + tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0]})) + + df["y"] = [0] + + assert df["a"].values[0] == -1 + tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0], "y": [0]}))