From 04eba89abeac273cf4d529562c6f3e509c6b098b Mon Sep 17 00:00:00 2001 From: Brock Date: Fri, 29 Jul 2022 13:32:42 -0700 Subject: [PATCH] BUG: preserve _id in MultiIndex.copy(deep=False) --- pandas/core/indexes/multi.py | 5 +++++ pandas/tests/indexes/multi/test_copy.py | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index fd6b6ba63d7e0..b4b576df9918e 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1190,6 +1190,7 @@ def copy( This could be potentially expensive on large MultiIndex objects. """ names = self._validate_names(name=name, names=names, deep=deep) + keep_id = not deep if levels is not None: warnings.warn( "parameter levels is deprecated and will be removed in a future " @@ -1197,6 +1198,7 @@ def copy( FutureWarning, stacklevel=find_stack_level(), ) + keep_id = False if codes is not None: warnings.warn( "parameter codes is deprecated and will be removed in a future " @@ -1204,6 +1206,7 @@ def copy( FutureWarning, stacklevel=find_stack_level(), ) + keep_id = False if deep: from copy import deepcopy @@ -1225,6 +1228,8 @@ def copy( ) new_index._cache = self._cache.copy() new_index._cache.pop("levels", None) # GH32669 + if keep_id: + new_index._id = self._id if dtype: warnings.warn( diff --git a/pandas/tests/indexes/multi/test_copy.py b/pandas/tests/indexes/multi/test_copy.py index 9a0e4bc0996be..2b64845c919cf 100644 --- a/pandas/tests/indexes/multi/test_copy.py +++ b/pandas/tests/indexes/multi/test_copy.py @@ -104,3 +104,15 @@ def test_copy_deprecated_parameters(deep, param_name, param_value): idx_copy = idx.copy(deep=deep, **{param_name: param_value}) assert [list(i) for i in getattr(idx_copy, param_name)] == param_value + + +def test_copy_deep_false_retains_id(): + # GH#47878 + idx = MultiIndex( + levels=[["foo", "bar"], ["fizz", "buzz"]], + codes=[[0, 0, 0, 1], [0, 0, 1, 1]], + names=["first", "second"], + ) + + res = idx.copy(deep=False) + assert res._id is idx._id