Sub topic 4
Why chained assignment stops working
This chapter assumes you know the Copy-on-Write rule from the earlier chapters: a DataFrame or Series derived from another object never changes the object it came from. It also assumes you are comfortable with .loc and basic Python references. Here you will see what that rule does to one old habit, chained assignment, and how to write the update correctly.
What chained assignment is
Chained assignment means two indexing steps in one statement, with an assignment at the end:
df["a"][0] = 100Python runs this as two separate operations:
df["a"]selects a column and returns a Series.Series.__setitem__(0, 100)writes into that Series.
The write in step 2 goes to whatever object step 1 returned. Whether that object is df or something else decides if the update reaches your data.
How it behaved before pandas 3
Before pandas 3, df["a"] sometimes returned a view of the column and sometimes a copy. The result depended on internal memory layout, dtypes, and how the DataFrame was built. The same line of code could update df on one input and silently do nothing on another. pandas tried to catch the failing cases with SettingWithCopyWarning, but the warning was neither complete nor reliable.
What happens in pandas 3
Under Copy-on-Write, df["a"] always returns an object that behaves as an independent copy. Writing to it can never change df. Chained assignment therefore never updates the original, and pandas tells you so.
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 first assignment modifies a temporary Series. That Series is discarded right after the statement, so df keeps the value 1. pandas detects this pattern and emits a ChainedAssignmentError warning. Treat it as a bug report on your own code: the statement does nothing useful.
The fix: one `.loc` call
Move the whole selection into a single .loc (or .iloc) call. That call has access to df itself, so it can write into it. The row selector goes first and the column selector second.
A boolean mask works the same way. The mask picks the rows, the column label picks the column, and both sit in one call:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
df.loc[df["foo"] > 1, "bar"] = 100
print(df)This prints:
foo bar
0 1 4
1 2 100
2 3 100The chained versions of this update are all broken in pandas 3:
df[df["foo"] > 1]["bar"] = 100 # writes into a filtered copy
df["bar"][df["foo"] > 1] = 100 # writes into a temporary column
df.loc[df["foo"] > 1]["bar"] = 100 # .loc, but still followed by a second stepThe last line is a common trap. It uses .loc, but the assignment comes after a second [...], so it is still a chain.
Common errors when fixing chains
- Splitting the chain across variables.
col = df["a"]followed bycol[0] = 100has the same problem.colis a derived object, so the write stays incol. This is the first rule of Copy-on-Write at work, not a special case. - Mixing up label and position.
df.loc[0, "a"]selects by index label.df.iloc[0, 0]selects by position. On a default RangeIndex they agree, but after filtering or sorting they do not. Pick the one that matches what you mean. - Ignoring the warning because the output looked right. Code that appeared to work in pandas 2.x may have relied on a view that happened to exist. Check the result after migrating.
- Expecting a filtered subset to write back.
subset = df[df["foo"] > 1]is an independent object. Updatingsubsetis fine as a way to work on a separate table, but it will never changedf.
A quick way to find chains in your code
Look for any line with an assignment whose left side contains two or more subscripts, such as x[...][...] = value. Rewrite each one so the left side is a single .loc[rows, column] or .iloc[rows, column]. If a warning appears at run time, the message points to the line that needs rewriting.
Exercise
This code is meant to set score to 0 for every row where passed is False, but df does not change in pandas 3. Rewrite the assignment so it works.
df = pd.DataFrame({"passed": [True, False, False], "score": [80, 45, 30]})
df[df["passed"] == False]["score"] = 0
Show answer
Use one .loc call with the row mask and the column label together: df.loc[~df["passed"], "score"] = 0 The original line first builds a filtered copy with df[...], then writes into that copy's "score" column. The write never reaches df, and pandas emits a ChainedAssignmentError warning. With a single .loc call, the assignment target is df itself. The result is score = [80, 0, 0].