Skip to content

ENH: Add lazy copy for series.reorder_levels #50472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 3, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4114,7 +4114,7 @@ def reorder_levels(self, order: Sequence[Level]) -> Series:
if not isinstance(self.index, MultiIndex): # pragma: no cover
raise Exception("Can only reorder levels on a hierarchical axis.")

result = self.copy()
result = self.copy(deep=None)
assert isinstance(result.index, MultiIndex)
result.index = result.index.reorder_levels(order)
return result
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,25 @@ def test_reorder_levels(using_copy_on_write):
tm.assert_frame_equal(df, df_orig)


def test_series_reorder_levels(using_copy_on_write):
index = MultiIndex.from_tuples(
[(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"]
)
ser = Series([1, 2, 3, 4], index=index)
ser_orig = ser.copy()
ser2 = ser.reorder_levels(order=["two", "one"])

if using_copy_on_write:
assert np.shares_memory(ser2.values, ser.values)
else:
assert not np.shares_memory(ser2.values, ser.values)

ser2.iloc[0] = 0
if using_copy_on_write:
assert not np.shares_memory(ser2.values, ser.values)
tm.assert_series_equal(ser, ser_orig)


def test_frame_set_axis(using_copy_on_write):
# GH 49473
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
Expand Down