Skip to content

Commit e4a710f

Browse files
committed
CoW: Add warning for replace with inplace (pandas-dev#56060)
1 parent 12a0487 commit e4a710f

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

pandas/core/generic.py

+16
Original file line numberDiff line numberDiff line change
@@ -7797,6 +7797,22 @@ def replace(
77977797
ChainedAssignmentError,
77987798
stacklevel=2,
77997799
)
7800+
elif not PYPY and not using_copy_on_write():
7801+
ctr = sys.getrefcount(self)
7802+
ref_count = REF_COUNT
7803+
if isinstance(self, ABCSeries) and hasattr(self, "_cacher"):
7804+
# in non-CoW mode, chained Series access will populate the
7805+
# `_item_cache` which results in an increased ref count not below
7806+
# the threshold, while we still need to warn. We detect this case
7807+
# of a Series derived from a DataFrame through the presence of
7808+
# `_cacher`
7809+
ref_count += 1
7810+
if ctr <= ref_count:
7811+
warnings.warn(
7812+
_chained_assignment_warning_method_msg,
7813+
FutureWarning,
7814+
stacklevel=2,
7815+
)
78007816

78017817
if not is_bool(regex) and to_replace is not None:
78027818
raise ValueError("'to_replace' must be 'None' if 'regex' is not a bool")

pandas/tests/copy_view/test_replace.py

+12
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from pandas import (
55
Categorical,
66
DataFrame,
7+
option_context,
78
)
89
import pandas._testing as tm
910
from pandas.tests.copy_view.util import get_array
@@ -395,6 +396,17 @@ def test_replace_chained_assignment(using_copy_on_write):
395396
with tm.raises_chained_assignment_error():
396397
df[["a"]].replace(1, 100, inplace=True)
397398
tm.assert_frame_equal(df, df_orig)
399+
else:
400+
with tm.assert_produces_warning(FutureWarning, match="inplace method"):
401+
with option_context("mode.chained_assignment", None):
402+
df[["a"]].replace(1, 100, inplace=True)
403+
404+
with tm.assert_produces_warning(FutureWarning, match="inplace method"):
405+
with option_context("mode.chained_assignment", None):
406+
df[df.a > 5].replace(1, 100, inplace=True)
407+
408+
with tm.assert_produces_warning(FutureWarning, match="inplace method"):
409+
df["a"].replace(1, 100, inplace=True)
398410

399411

400412
def test_replace_listlike(using_copy_on_write):

0 commit comments

Comments
 (0)