Skip to content

Commit 474a528

Browse files
authored
ENH: add copy on write for df reorder_levels GH49473 (#50016)
1 parent 0bcbdf9 commit 474a528

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

pandas/core/frame.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -7407,7 +7407,7 @@ def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame:
74077407
result.columns = result.columns.swaplevel(i, j)
74087408
return result
74097409

7410-
def reorder_levels(self, order: Sequence[Axis], axis: Axis = 0) -> DataFrame:
7410+
def reorder_levels(self, order: Sequence[int | str], axis: Axis = 0) -> DataFrame:
74117411
"""
74127412
Rearrange index levels using input order. May not drop or duplicate levels.
74137413
@@ -7452,7 +7452,7 @@ class diet
74527452
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
74537453
raise TypeError("Can only reorder levels on a hierarchical axis.")
74547454

7455-
result = self.copy()
7455+
result = self.copy(deep=None)
74567456

74577457
if axis == 0:
74587458
assert isinstance(result.index, MultiIndex)

pandas/tests/copy_view/test_methods.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from pandas import (
55
DataFrame,
6+
MultiIndex,
67
Series,
78
)
89
import pandas._testing as tm
@@ -293,7 +294,25 @@ def test_assign(using_copy_on_write):
293294
else:
294295
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
295296

296-
# modify df2 to trigger CoW for that block
297+
df2.iloc[0, 0] = 0
298+
if using_copy_on_write:
299+
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
300+
tm.assert_frame_equal(df, df_orig)
301+
302+
303+
def test_reorder_levels(using_copy_on_write):
304+
index = MultiIndex.from_tuples(
305+
[(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"]
306+
)
307+
df = DataFrame({"a": [1, 2, 3, 4]}, index=index)
308+
df_orig = df.copy()
309+
df2 = df.reorder_levels(order=["two", "one"])
310+
311+
if using_copy_on_write:
312+
assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
313+
else:
314+
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
315+
297316
df2.iloc[0, 0] = 0
298317
if using_copy_on_write:
299318
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))

0 commit comments

Comments
 (0)