Skip to content

CoW: Add ChainedAssignmentError for replace with inplace=True #54023

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
Jul 17, 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Copy-on-Write improvements

- DataFrame.update / Series.update
- DataFrame.fillna / Series.fillna
- DataFrame.replace / Series.replace

.. _whatsnew_210.enhancements.enhancement2:

Expand Down
9 changes: 9 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7623,6 +7623,15 @@ def replace(
)

inplace = validate_bool_kwarg(inplace, "inplace")
if inplace:
if not PYPY and using_copy_on_write():
if sys.getrefcount(self) <= REF_COUNT:
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)

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

Expand Down
3 changes: 2 additions & 1 deletion pandas/tests/arrays/categorical/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ def test_replace_categorical(to_replace, value, result, expected_error_msg):
# ensure non-inplace call does not affect original
tm.assert_categorical_equal(cat, expected)

pd.Series(cat, copy=False).replace(to_replace, value, inplace=True)
ser = pd.Series(cat, copy=False)
ser.replace(to_replace, value, inplace=True)
tm.assert_categorical_equal(cat, expected)


Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/copy_view/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,3 +373,16 @@ def test_replace_columnwise_no_op(using_copy_on_write):
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
df2.iloc[0, 0] = 100
tm.assert_frame_equal(df, df_orig)


def test_replace_chained_assignment(using_copy_on_write):
df = DataFrame({"a": [1, np.nan, 2], "b": 1})
df_orig = df.copy()
if using_copy_on_write:
with tm.raises_chained_assignment_error():
df["a"].replace(1, 100, inplace=True)
tm.assert_frame_equal(df, df_orig)

with tm.raises_chained_assignment_error():
df[["a"]].replace(1, 100, inplace=True)
tm.assert_frame_equal(df, df_orig)