Repository: pandas-dev/pandas
Pull request: BUG: DataFrame._item_cache not cleared on on .copy()
- [x] closes #31784
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry


Problem statement:
BUG: DataFrame._item_cache not cleared on on .copy()
#### Code Sample, a copy-pastable example if possible

import copy
import pandas as pd
import platform

print('Python Version', platform.python_version())
print('Pandas Version', pd.__version__)

a = [1.]
    
d = {}
d['a'] = a 
df = pd.DataFrame(d)

print('Initial data frame')
print(df)
print('------')

\# This statement must be before the print statement
\# Removing this causes the bug to disappear
df['x'] = 0.0

\# Removing this causes the bug to disappear
print("df['a'].values=", df['a'].values)
print('-----')

\# Removing the copy causes the bug to disappear
\# copy.deepcopy(df) or df.copy() leads to the same result
\#df1 = copy.deepcopy(df) 
df1 = df.copy()

\# set the first element of 'a' to value 
value = -1.0
df['a'].values[0] = value

print("After setting df['a'].values[0] = %f" % (value))
print(df)
print('-------')

print("df['a'].values=", df['a'].values)
print('-------')

\# Removing this causes the bug to disappear
df['y'] = 0.0

print('Final')
print(df)
print('-------')

print("df['a'].values=", df['a'].values)
    
#### Problem description

First, we build a dataframe from a dictionary containing a list. 

After that, we add  a column, do add some print statements, copy the dataframe. The addition of the column and print statement are crucial to the bug showing up. The fact that the print statement matters leads me to believe that it's memory issue.

The critical point is that we set df['a'].values[0] = -1.0 which is somehow not permanent.

Lastly we add another column. This column addition is necessary for the issue to occur.

In short the issue looks like this:

a = [1.0]

df = pd.DataFrame({'a': a})
df['x'] = 0.0 # necessary for bug
print(df['a'].values) # necessary for bug
df1 = df.copy()
df['a'].values[0] = -1.0 # this is the statement which is ignored
print(df['a'].values)
print(df)
df['y'] = 0.0 # necessary for bug
print(df['a'].values)

At this point, we'd expect df['a'].values = [-1.0], but in fact df['a'].values == 1.0 

I've tested this issue on a wide variety of versions. The last version where it works as expected is 0.16.2 and the version with the unexpected result is 0.17.1. I've tried this with python 3.6 / pandas=1.0.0 on Linux and python 3.7 / pandas 1.0.1 on OS X and get the same result. 


<details>
INSTALLED VERSIONS
------------------
commit           : None
python           : 3.7.0.final.0
python-bits      : 64
OS               : Darwin
OS-release       : 17.7.0
machine          : x86_64
processor        : i386
byteorder        : little
LC_ALL           : None
LANG             : en_US.UTF-8
LOCALE           : en_US.UTF-8

pandas           : 1.0.1
numpy            : 1.15.1
pytz             : 2019.3
dateutil         : 2.7.3
pip              : 18.0
setuptools       : 40.2.0
Cython           : None
pytest           : None
hypothesis       : None
sphinx           : None
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : 1.0.1
pymysql          : None
psycopg2         : None
jinja2           : 2.10
IPython          : 6.5.0
pandas_datareader: None
bs4              : None
bottleneck       : None
fastparquet      : None
gcsfs            : None
lxml.etree       : None
matplotlib       : None
numexpr          : None
odfpy            : None
openpyxl         : None
pandas_gbq       : None
pyarrow          : None
pytables         : None
pytest           : None
pyxlsb           : None
s3fs             : None
scipy            : None
sqlalchemy       : None
tables           : None
tabulate         : None
xarray           : None
xlrd             : None
xlwt             : None
xlsxwriter       : None
numba            : None
None

</details>

Hints from issue discussion:
It looks like the issue is that `df._item_cache` is not being invalidated correctly after the `df.copy()` call performs consolidation.  A PR to fix this would be welcome.
take

Commit message: #33299 updated tests

Patch to review:
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 8bff34dbdadad..0482b0b74cee4 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -363,6 +363,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 invalidated after copy performs consolidation (:issue: `31784`)
 
 Missing
 ^^^^^^^
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index c202bf846047f..be939519014e2 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5680,6 +5680,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/generic/test_generic.py b/pandas/tests/generic/test_generic.py
index 1a4a0b1678aa4..f34e232744311 100644
--- a/pandas/tests/generic/test_generic.py
+++ b/pandas/tests/generic/test_generic.py
@@ -910,3 +910,21 @@ def test_axis_classmethods(self, box):
             assert obj._get_axis_number(v) == box._get_axis_number(v)
             assert obj._get_axis_name(v) == box._get_axis_name(v)
             assert obj._get_block_manager_axis(v) == box._get_block_manager_axis(v)
+
+    def test_cache_on_copy(self):
+        df = DataFrame({"a": [1]})
+
+        df["x"] = [0]
+        df["a"]
+
+        df.copy()
+
+        df["a"].values[0] = -1
+
+        assert 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]}))


Code review comments:
diff_hunk: @@ -363,6 +363,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 invalidated after copy performs consolidation (:issue: `31784`)
path: doc/source/whatsnew/v1.1.0.rst
text: @user1:
I *think* this is needed for it to be rendered correctly
```suggestion
- Bug in :meth:`DataFrame.copy` _item_cache invalidated after copy performs consolidation (:issue:`31784`)
```