Skip to content

BUG/CoW: Series.rename not making a lazy copy when passed a scalar #53189

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 4 commits into from
May 14, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Bug fixes
- Bug in :meth:`DataFrame.__getitem__` not preserving dtypes for :class:`MultiIndex` partial keys (:issue:`51895`)
- Bug in :meth:`DataFrame.convert_dtypes` ignores ``convert_*`` keywords when set to False ``dtype_backend="pyarrow"`` (:issue:`52872`)
- Bug in :meth:`Series.describe` treating pyarrow-backed timestamps and timedeltas as categorical data (:issue:`53001`)
- Bug in :meth:`Series.rename` not making a lazy copy when Copy-on-Write is enabled when a scalar is passed to it (:issue:`52450`)
- Bug in :meth:`pd.array` raising for ``NumPy`` array and ``pa.large_string`` or ``pa.large_binary`` (:issue:`52590`)


Expand Down
14 changes: 10 additions & 4 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1907,7 +1907,9 @@ def to_frame(self, name: Hashable = lib.no_default) -> DataFrame:
df = self._constructor_expanddim(mgr)
return df.__finalize__(self, method="to_frame")

def _set_name(self, name, inplace: bool = False) -> Series:
def _set_name(
self, name, inplace: bool = False, deep: bool | None = None
) -> Series:
"""
Set the Series name.

Expand All @@ -1916,9 +1918,11 @@ def _set_name(self, name, inplace: bool = False) -> Series:
name : str
inplace : bool
Whether to modify `self` directly or return a copy.
deep : bool|None, default None
Whether to do a deep copy, a shallow copy, or Copy on Write(None)
"""
inplace = validate_bool_kwarg(inplace, "inplace")
ser = self if inplace else self.copy()
ser = self if inplace else self.copy(deep)
ser.name = name
return ser

Expand Down Expand Up @@ -4580,7 +4584,7 @@ def rename(
index: Renamer | Hashable | None = None,
*,
axis: Axis | None = None,
copy: bool = True,
copy: bool | None = None,
inplace: bool = False,
level: Level | None = None,
errors: IgnoreRaise = "ignore",
Expand Down Expand Up @@ -4667,7 +4671,9 @@ def rename(
errors=errors,
)
else:
return self._set_name(index, inplace=inplace)
return self._set_name(
index, inplace=inplace, deep=copy 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.

Any reason we are doing this here and not in _set_name?

Copy link
Member

Choose a reason for hiding this comment

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

Simply passing copy through should be sufficient though

Copy link
Member Author

Choose a reason for hiding this comment

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

It's to ignore copy=True, when Copy on Write is activated. I just copy pasted from your code in #51464

Copy link
Member

Choose a reason for hiding this comment

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

Forgot about this, thx.

Copy link
Member Author

Choose a reason for hiding this comment

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

Nothing else calls _set_name other than rename, so I just left the Copy on Write logic in rename itself. I can move it if you want me to.

Copy link
Member

Choose a reason for hiding this comment

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

Probably more consistent to push it down, but not a really strong opinion

)

@Appender(
"""
Expand Down
2 changes: 2 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ def test_methods_copy_keyword(
"method",
[
lambda ser, copy: ser.rename(index={0: 100}, copy=copy),
lambda ser, copy: ser.rename(None, copy=copy),
lambda ser, copy: ser.reindex(index=ser.index, copy=copy),
lambda ser, copy: ser.reindex_like(ser, copy=copy),
lambda ser, copy: ser.align(ser, copy=copy)[0],
Expand All @@ -158,6 +159,7 @@ def test_methods_copy_keyword(
lambda ser, copy: ser.set_flags(allows_duplicate_labels=False, copy=copy),
],
ids=[
"rename (dict)",
"rename",
"reindex",
"reindex_like",
Expand Down
8 changes: 6 additions & 2 deletions pandas/tests/frame/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def test_frame_setitem_existing_datetime64_col_other_units(self, unit):
df["dates"] = vals
assert (df["dates"].values == ex_vals).all()

def test_setitem_dt64tz(self, timezone_frame):
def test_setitem_dt64tz(self, timezone_frame, using_copy_on_write):
df = timezone_frame
idx = df["B"].rename("foo")

Expand All @@ -331,12 +331,16 @@ def test_setitem_dt64tz(self, timezone_frame):

# assert that A & C are not sharing the same base (e.g. they
# are copies)
# Note: This does not hold with Copy on Write (because of lazy copying)
v1 = df._mgr.arrays[1]
v2 = df._mgr.arrays[2]
tm.assert_extension_array_equal(v1, v2)
v1base = v1._ndarray.base
v2base = v2._ndarray.base
assert v1base is None or (id(v1base) != id(v2base))
if not using_copy_on_write:
assert v1base is None or (id(v1base) != id(v2base))
else:
assert id(v1base) == id(v2base)

# with nan
df2 = df.copy()
Expand Down