Skip to content

ENH: add lazy copy (CoW) mechanism to rename_axis #50415

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 6 commits into from
Jan 2, 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
17 changes: 12 additions & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1209,7 +1209,8 @@ class name
axes, kwargs = self._construct_axes_from_arguments(
(), kwargs, sentinel=lib.no_default
)
copy = kwargs.pop("copy", True)
copy: bool_t | None = kwargs.pop("copy", None)

inplace = kwargs.pop("inplace", False)
axis = kwargs.pop("axis", 0)
if axis is not None:
Expand All @@ -1229,7 +1230,9 @@ class name
is_list_like(mapper) and not is_dict_like(mapper)
)
if non_mapper:
return self._set_axis_name(mapper, axis=axis, inplace=inplace)
return self._set_axis_name(
mapper, axis=axis, inplace=inplace, copy=copy
)
else:
raise ValueError("Use `.rename` to alter labels with a mapper.")
else:
Expand All @@ -1248,13 +1251,15 @@ class name
f = common.get_rename_function(v)
curnames = self._get_axis(axis).names
newnames = [f(name) for name in curnames]
result._set_axis_name(newnames, axis=axis, inplace=True)
result._set_axis_name(newnames, axis=axis, inplace=True, copy=copy)
if not inplace:
return result
return None

@final
def _set_axis_name(self, name, axis: Axis = 0, inplace: bool_t = False):
def _set_axis_name(
self, name, axis: Axis = 0, inplace: bool_t = False, copy: bool_t | None = True
):
"""
Set the name(s) of the axis.

Expand All @@ -1267,6 +1272,8 @@ def _set_axis_name(self, name, axis: Axis = 0, inplace: bool_t = False):
and the value 1 or 'columns' specifies columns.
inplace : bool, default False
If `True`, do operation inplace and return None.
copy:
Whether to make a copy of the result.

Returns
-------
Expand Down Expand Up @@ -1308,7 +1315,7 @@ def _set_axis_name(self, name, axis: Axis = 0, inplace: bool_t = False):
idx = self._get_axis(axis).set_names(name)

inplace = validate_bool_kwarg(inplace, "inplace")
renamed = self if inplace else self.copy()
renamed = self if inplace else self.copy(deep=copy)
if axis == 0:
renamed.index = idx
else:
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 @@ -3,6 +3,7 @@

from pandas import (
DataFrame,
Index,
MultiIndex,
Series,
)
Expand Down Expand Up @@ -456,3 +457,21 @@ def test_series_set_axis(using_copy_on_write):
ser2.iloc[0] = 0
assert not np.shares_memory(ser2, ser)
tm.assert_series_equal(ser, ser_orig)


@pytest.mark.parametrize("copy_kwargs", [{"copy": True}, {}])
@pytest.mark.parametrize("kwargs", [{"mapper": "test"}, {"index": "test"}])
def test_rename_axis(using_copy_on_write, kwargs, copy_kwargs):
df = DataFrame({"a": [1, 2, 3, 4]}, index=Index([1, 2, 3, 4], name="a"))
df_orig = df.copy()
df2 = df.rename_axis(**kwargs, **copy_kwargs)

if using_copy_on_write and not copy_kwargs:
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"))
tm.assert_frame_equal(df, df_orig)