Skip to content

ENH: Add lazy copy for swapaxes no op #50573

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 7 commits into from
Jan 12, 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
8 changes: 4 additions & 4 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,7 @@ def _set_axis(self, axis: AxisInt, labels: AnyArrayLike | list) -> None:

@final
def swapaxes(
self: NDFrameT, axis1: Axis, axis2: Axis, copy: bool_t = True
self: NDFrameT, axis1: Axis, axis2: Axis, copy: bool_t | None = None
) -> NDFrameT:
"""
Interchange axes and swap values axes appropriately.
Expand All @@ -774,9 +774,9 @@ def swapaxes(
j = self._get_axis_number(axis2)

if i == j:
if copy:
return self.copy()
return self
if not copy and copy is not None and not _using_copy_on_write():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if not copy and copy is not None and not _using_copy_on_write():
if copy is False and not _using_copy_on_write():

return self
return self.copy(deep=copy)

mapping = {i: j, j: i}

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 @@ -255,6 +255,24 @@ def test_to_frame(using_copy_on_write):
tm.assert_frame_equal(df, expected)


@pytest.mark.parametrize("ax", ["index", "columns"])
def test_swapaxes_noop(using_copy_on_write, ax):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df_orig = df.copy()
df2 = df.swapaxes(ax, ax)

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"))

# mutating df2 triggers a copy-on-write for that column/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)


@pytest.mark.parametrize(
"method, idx",
[
Expand Down