Sub topic 4
Why chained assignment stops working
This chapter assumes you know basic pandas selection with [], .loc and .iloc. It also assumes you know that Python objects are references to mutable data. You should have read the chapter on the Copy-on-Write rule: any DataFrame or Series derived from another object behaves as an independent copy.
By the end of the chapter you will be able to explain why df["a"][0] = 100 can't update df, rewrite it as one .loc call, and read the ChainedAssignmentError warning.
What chained assignment is
Chained assignment is an assignment where the target is reached through two or more indexing operations in a row:
df["a"][0] = 100
df[df["foo"] > 1]["bar"] = 100
df.loc[df["foo"] > 1]["bar"] = 100Each line contains two steps:
- A selection, such as
df["a"],df[mask]ordf.loc[mask]. It returns a new object. - A write, such as
[0] = 100or["bar"] = 100, applied to that new object.
The write in step 2 goes to whatever object step 1 returned. In pandas 2.x, step 1 might return a view of df, so the write sometimes reached df. Whether it did depended on the dtypes, the index and the kind of selection. That is the view-or-copy ambiguity described in the first chapter of this tutorial.
What happens under Copy-on-Write
Copy-on-Write has one rule: a derived object never changes the object it came from. The result of df["a"] is derived from df, so it behaves as an independent copy. Writing to it changes only that Series.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
col = df["a"]
col.iloc[0] = 100
print(col.iloc[0]) # 100
print(df["a"].iloc[0]) # 1, df is unchangedChained assignment is the same situation with one difference: you never gave the derived object a name. Python creates it, applies your write, and discards it.
import warnings
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
df["a"][0] = 100
print([w.category.__name__ for w in caught]) # ['ChainedAssignmentError']
print(df["a"].tolist()) # [1, 2, 3], df is unchangedThe write succeeded, but on a temporary Series that was thrown away immediately afterwards. Nothing was written to df.
Reading the ChainedAssignmentError warning
pandas 3 detects most chained assignments and emits a ChainedAssignmentError. Despite the name, it is a warning, not an exception. Your program keeps running and df keeps its old values. This is the failure mode to watch for: the code appears to work, and the data is simply wrong.
pandas detects the pattern by noticing that the object being written to is a temporary that nothing else refers to. That has two consequences:
- The warning message points you to the line that needs rewriting. Treat it as a bug report, not as noise.
- If you store the intermediate object in a variable first, the object is no longer a temporary and the warning does not appear. The write still doesn't reach
df, because the Copy-on-Write rule holds either way.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
col = df["a"] # a named object, so no warning
col[0] = 100 # modifies col only
print(df["a"].tolist()) # [1, 2, 3]The absence of a warning therefore does not mean the code is correct. Check where each write lands.
If you want your test suite to catch these, turn the warning into an error:
import warnings
import pandas as pd
from pandas.errors import ChainedAssignmentError
warnings.simplefilter("error", ChainedAssignmentError)
df = pd.DataFrame({"a": [1, 2, 3]})
try:
df["a"][0] = 100
except ChainedAssignmentError:
print("chained assignment caught")In a pytest project, the equivalent is filterwarnings = error::pandas.errors.ChainedAssignmentError in your configuration.
The fix: one assignment on the original object
To change df, perform the write on df itself in a single call. .loc takes the row selector and the column selector together, so pandas knows exactly which cells of which object to write.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
# Chained assignment: modifies a temporary object and emits a ChainedAssignmentError warning.
df["a"][0] = 100
print(df["a"].iloc[0]) # 1, df is unchanged
# Single-step assignment with .loc updates df itself.
df.loc[0, "a"] = 100
print(df["a"].iloc[0]) # 100The .loc[row, column] form is one method call on df. There is no intermediate object, so nothing can be lost.
Updating rows chosen by a condition
The most common chained assignment in real code is "set a column where some condition holds". Put the boolean mask in the row position and the column label in the column position:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
df.loc[df["foo"] > 1, "bar"] = 100
print(df)The output is:
foo bar
0 1 4
1 2 100
2 3 100The broken version of the same operation is df[df["foo"] > 1]["bar"] = 100. It first builds a filtered DataFrame (a new object), then sets the column bar on that new object. The original df never sees the change.
Other forms that work
| Goal | Single-step form |
|---|---|
| Set one cell by label | `df.loc[0, "a"] = 100` |
| Set one cell by position | `df.iloc[0, 0] = 100` |
| Set a column where a mask is true | `df.loc[mask, "bar"] = 100` |
| Set several columns where a mask is true | `df.loc[mask, ["foo", "bar"]] = 0` |
| Replace a whole column | `df["bar"] = 0` |
| Build a new DataFrame with the change | `df = df.assign(bar=...)` |
Two details are easy to miss.
df["bar"] = 0is not chained assignment. It is a single__setitem__call ondf, and it replaces the column. The same applies todf["new_col"] = ....- With
.iloc, the mask must be positional. A boolean Series with a mismatched index works with.loc(pandas aligns on labels), but.ilocexpects a plain array or list of booleans. Use.locwith a mask unless you have a specific reason not to.
Chained patterns that look different but fail the same way
The two-bracket form is the obvious one. These variants have the same cause.
A method between the two steps. Any method that returns a new object breaks the chain:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
df.query("foo > 1")["bar"] = 100 # writes to the query result, not df
df.loc[df["foo"] > 1]["bar"] = 100 # writes to the filtered copy, not df
print(df["bar"].tolist()) # [4, 5, 6]Selecting a column first, then masking. This form is reasonable-looking and equally broken:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
df["bar"][df["foo"] > 1] = 100 # df["bar"] is a temporary Series
print(df["bar"].tolist()) # [4, 5, 6]The fix is the one you already know: df.loc[df["foo"] > 1, "bar"] = 100.
Assigning through a slice you kept. A variable holding a filtered frame is independent of df as well:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
subset = df[df["foo"] > 1]
subset.loc[:, "bar"] = 0
print(df["bar"].tolist()) # [4, 5, 6], df is unchanged
print(subset["bar"].tolist()) # [0, 0]This code is correct if you want to change only subset. If you wanted to change df, write to df with a mask, as above.
Why pandas did not keep the old behavior
In pandas 2.x, code like df["a"][0] = 100 worked in some cases and failed in others. A single-dtype DataFrame often gave views, so the write reached df. A mixed-dtype DataFrame often gave copies, so it didn't. pandas tried to detect the failing cases and raised SettingWithCopyWarning, but the detection was a heuristic with both false positives and false negatives. Some correct code warned, and some broken code stayed silent.
Copy-on-Write replaces the heuristic with a rule that does not depend on dtypes or the shape of the data. The result of any selection is independent of its parent, so writing through a temporary can never update the parent. SettingWithCopyWarning no longer exists in pandas 3. ChainedAssignmentError is a simpler check. It flags the pattern that is always wrong, instead of guessing whether it might be wrong.
The cost is that some pandas 2.x code that happened to work now silently does nothing. That is the reason to treat every ChainedAssignmentError as a real bug.
A checklist for finding and fixing chained assignment
- Search your code for a second
[or.loc[or.iloc[on the left side of an=. - Identify the root object you want to change. This is usually a DataFrame, such as
df. - Rewrite the line as
root.loc[row_selector, column_selector] = value. - Run the code with
ChainedAssignmentErrorturned into an error, so any remaining cases fail loudly. - Verify with a small input that the original object changes.
import pandas as pd
df = pd.DataFrame(
{"city": ["Oslo", "Lima", "Kyiv"], "temp_c": [-3.0, 19.5, 2.0]}
)
# Before (pandas 2.x habit, wrong in pandas 3):
# df[df["temp_c"] < 5]["label"] = "cold"
# After:
df["label"] = "mild"
df.loc[df["temp_c"] < 5, "label"] = "cold"
print(df)The output is:
city temp_c label
0 Oslo -3.0 cold
1 Lima 19.5 mild
2 Kyiv 2.0 coldNote that the column label is created first with a plain df["label"] = .... With .loc, you can also create the column in the same call. Rows that don't match the mask then get NaN, so setting a default first is often clearer.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `ChainedAssignmentError` warning, data unchanged | Two indexing steps before the `=` | Single `.loc[rows, cols] = value` |
| No warning, data unchanged | Write went to a named intermediate variable | Write to the original object |
| Column created on a filtered copy only | `df[mask]["new"] = ...` | `df.loc[mask, "new"] = ...` |
| `NaN` in rows outside the mask | `.loc` created a new column | Set a default first, or use `.where` or `np.where` |
Summary of the mechanism
A selection returns a new object. Under Copy-on-Write that object is independent of its parent. Chained assignment writes to the new object and drops it, so the parent is untouched. The fix is to name the parent, the rows and the columns in one .loc call.
Exercise
This code is meant to give every product priced under 10 a "budget" tier. It runs without raising an exception, but df["tier"] is still all "standard" afterwards. Explain why, and rewrite the last line so it works.
import pandas as pd
df = pd.DataFrame({"item": ["pen", "lamp", "cup"], "price": [2.5, 40.0, 8.0]})
df["tier"] = "standard"
df[df["price"] < 10]["tier"] = "budget"
Show answer
df[df["price"] < 10] builds a new filtered DataFrame that is independent of df. The assignment ["tier"] = "budget" then sets the column on that temporary object, which is discarded. pandas also emits a ChainedAssignmentError warning. The fix is one call on the original object: df.loc[df["price"] < 10, "tier"] = "budget". After it, "pen" and "cup" have tier "budget" and "lamp" stays "standard".
Exercise
A colleague "fixes" the warning in df["a"][0] = 100 by writing col = df["a"] and then col[0] = 100. The warning disappears. Does df now contain 100 at position 0? Explain.
Show answer
No. The warning disappears because col is a named variable, not a temporary object. The Copy-on-Write rule still applies. df["a"] is derived from df, so it acts as an independent copy, and the write changes only col. df["a"].iloc[0] is still the original value. The correct fix is df.loc[0, "a"] = 100.
Exercise
Which of these lines modify df? (a) df["x"] = 0, (b) df["x"][df["y"] > 0] = 0, (c) df.loc[df["y"] > 0, "x"] = 0, (d) df.query("y > 0")["x"] = 0.
Show answer
(a) and (c). Line (a) is a single __setitem__ call on df that replaces column x. Line (c) is a single .loc call on df with a mask and a column label. Lines (b) and (d) are chained assignment: (b) writes to the temporary Series df["x"], and (d) writes to the temporary DataFrame returned by query. Neither writes to df.