diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c7f0a7ced7576..eb3365d4f8410 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7407,7 +7407,7 @@ def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame: result.columns = result.columns.swaplevel(i, j) return result - def reorder_levels(self, order: Sequence[Axis], axis: Axis = 0) -> DataFrame: + def reorder_levels(self, order: Sequence[int | str], axis: Axis = 0) -> DataFrame: """ Rearrange index levels using input order. May not drop or duplicate levels. @@ -7452,7 +7452,7 @@ class diet if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover raise TypeError("Can only reorder levels on a hierarchical axis.") - result = self.copy() + result = self.copy(deep=None) if axis == 0: assert isinstance(result.index, MultiIndex) diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 6707f1411cbc7..8015eb93988c9 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -3,6 +3,7 @@ from pandas import ( DataFrame, + MultiIndex, Series, ) import pandas._testing as tm @@ -293,7 +294,25 @@ def test_assign(using_copy_on_write): else: assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) - # modify df2 to trigger CoW for that block + df2.iloc[0, 0] = 0 + if using_copy_on_write: + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + tm.assert_frame_equal(df, df_orig) + + +def test_reorder_levels(using_copy_on_write): + index = MultiIndex.from_tuples( + [(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"] + ) + df = DataFrame({"a": [1, 2, 3, 4]}, index=index) + df_orig = df.copy() + df2 = df.reorder_levels(order=["two", "one"]) + + if using_copy_on_write: + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + else: + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + df2.iloc[0, 0] = 0 if using_copy_on_write: assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))