Skip to content

ENH: Add lazy copy to swaplevel #50478

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 1 commit into from
Jan 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -7254,7 +7254,7 @@ def nsmallest(self, n: int, columns: IndexLabel, keep: str = "first") -> DataFra
),
)
def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame:
result = self.copy()
result = self.copy(deep=None)

axis = self._get_axis_number(axis)

Expand Down
11 changes: 6 additions & 5 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4071,7 +4071,9 @@ def nsmallest(self, n: int = 5, keep: str = "first") -> Series:
dtype: object"""
),
)
def swaplevel(self, i: Level = -2, j: Level = -1, copy: bool = True) -> Series:
def swaplevel(
self, i: Level = -2, j: Level = -1, copy: bool | None = None
) -> Series:
"""
Swap levels i and j in a :class:`MultiIndex`.

Expand All @@ -4091,10 +4093,9 @@ def swaplevel(self, i: Level = -2, j: Level = -1, copy: bool = True) -> Series:
{examples}
"""
assert isinstance(self.index, MultiIndex)
new_index = self.index.swaplevel(i, j)
return self._constructor(self._values, index=new_index, copy=copy).__finalize__(
self, method="swaplevel"
)
result = self.copy(deep=copy)
result.index = self.index.swaplevel(i, j)
return result

def reorder_levels(self, order: Sequence[Level]) -> Series:
"""
Expand Down
18 changes: 18 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,24 @@ def test_reorder_levels(using_copy_on_write):
tm.assert_frame_equal(df, df_orig)


@pytest.mark.parametrize("obj", [Series([1, 2, 3]), DataFrame({"a": [1, 2, 3]})])
def test_swaplevel(using_copy_on_write, obj):
index = MultiIndex.from_tuples([(1, 1), (1, 2), (2, 1)], names=["one", "two"])
obj.index = index
obj_orig = obj.copy()
obj2 = obj.swaplevel()

if using_copy_on_write:
assert np.shares_memory(obj2.values, obj.values)
else:
assert not np.shares_memory(obj2.values, obj.values)

obj2.iloc[0] = 0
if using_copy_on_write:
assert not np.shares_memory(obj2.values, obj.values)
tm.assert_equal(obj, obj_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