Sub topic 15
Avoiding chained assignment and copy warnings
This chapter assumes you can build a DataFrame, select columns by name, and add a column with df["name"] = .... You should also know boolean masks such as df["price"] > 5. The chapter explains why some assignments silently fail, what the warnings mean, and which patterns are safe.
Why pandas warns you
Every time you write df[...], pandas returns a new object. Sometimes that object is a copy with its own data. Sometimes it is a view that shares memory with the original. Which one you get depends on the indexer, the dtypes, and the pandas version, and older pandas did not document it clearly.
That uncertainty causes trouble when you assign into the result of a selection. You may be changing the original DataFrame, or you may be changing a temporary object that is discarded a moment later.
Chained assignment is an assignment that uses two or more indexing steps in a row:
df[df["qty"] > 2]["total"] = 0Python runs this as two separate operations:
df[df["qty"] > 2]runs__getitem__and returns a temporary DataFrame.["total"] = 0runs__setitem__on that temporary object.
Whether the temporary object points back to df is not something you should rely on.
The three behaviors by version
| pandas version | Behavior of chained assignment |
|---|---|
| 1.x and 2.x (default) | Sometimes updates the original, sometimes not. Often emits `SettingWithCopyWarning`. |
| 2.x with Copy-on-Write enabled | Never updates the original. Emits a warning in recent 2.x releases. |
| 3.0 and later | Copy-on-Write is always on. The original is never updated, and pandas emits `ChainedAssignmentError`. |
In pandas 2.x you can opt in to the new behavior with pd.options.mode.copy_on_write = True. The fixes in this chapter work in every version. Write code that is correct under Copy-on-Write and you can ignore the version question.
Copy-on-Write in one paragraph
Under Copy-on-Write (CoW), any result of an indexing operation behaves as a separate object. pandas may share memory internally for speed. The first time you modify one object, it quietly copies the data it needs. Changing a derived object can therefore never change its parent. This removes the view-or-copy guessing game, and it also means chained assignment has nothing to write to.
Fix 1: one step with `.loc`
To change some rows of a column in the original, give .loc the row selector and the column together. The write then happens in a single __setitem__ call on df itself.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
df["total"] = df["price"] * df["qty"]
# Wrong: two indexing steps. The write goes to a temporary object.
# df[df["qty"] > 2]["total"] = 0
# Right: one step on df.
df.loc[df["qty"] > 2, "total"] = 0.0
print(df)The output is:
item price qty total
0 pen 1.5 10 0.0
1 book 12.0 3 0.0
2 lamp 30.0 2 60.0.loc also creates a column when the name does not exist yet. Rows that the mask does not select get NaN:
df.loc[df["price"] > 10, "premium"] = True
print(df["premium"].tolist()) # [nan, True, True]Because of the NaN values, this column has object dtype, not bool. If you want a clean True/False column, assign the comparison directly: df["premium"] = df["price"] > 10.
Fix 2: `.copy()` when you want a separate table
Selecting a subset and then adding a column to it is the other common source of SettingWithCopyWarning:
expensive = df[df["price"] > 5]
expensive["discounted"] = expensive["price"] * 0.9 # warns in pandas 2.xThe warning exists because pandas cannot tell whether you meant to change df or only expensive. Say which one you mean. If the subset is a new, independent table, call .copy() when you create it:
expensive = df[df["price"] > 5].copy()
expensive["discounted"] = expensive["price"] * 0.9
print(expensive[["item", "discounted"]])Under CoW the .copy() is not strictly required, because the subset is already independent. Keep it anyway. It states your intent and silences the warning on older versions. You can also avoid the problem by not assigning at all, and using assign() from earlier in this tutorial:
expensive = df[df["price"] > 5].assign(discounted=lambda d: d["price"] * 0.9)Fix 3: assign the result back instead of using `inplace`
A second kind of chained assignment hides inside methods that take inplace=True. This line looks harmless:
df["discount"] = [0.1, np.nan, 0.2]
df["discount"].fillna(0.0, inplace=True) # chained: modifies a temporary Seriesdf["discount"] yields a temporary Series, and fillna(..., inplace=True) modifies that Series. Under CoW the original DataFrame is not updated. Pandas 2.x and later warn about this pattern. Assign the result back:
df["discount"] = df["discount"].fillna(0.0)
print(df["discount"].tolist()) # [0.1, 0.0, 0.2]The same rule applies to df["col"].replace(..., inplace=True) and to df["col"].iloc[0] = value. If the assignment starts with df["col"] and continues with another operation, you are chaining.
Quick reference
| Goal | Unsafe pattern | Safe pattern |
|---|---|---|
| Set values for some rows | `df[mask]["col"] = v` | `df.loc[mask, "col"] = v` |
| Set one cell by position | `df["col"].iloc[0] = v` | `df.iloc[0, df.columns.get_loc("col")] = v` |
| Fill missing values | `df["col"].fillna(0, inplace=True)` | `df["col"] = df["col"].fillna(0)` |
| Work on a subset | `sub = df[mask]; sub["x"] = 1` | `sub = df[mask].copy(); sub["x"] = 1` |
| Conditional column | `df[mask]["x"] = "a"` | `df["x"] = np.where(mask, "a", "b")` |
Behaviors to expect under Copy-on-Write
- Derived objects are independent. After
s = df["price"], changingsleavesdfunchanged. If you want the change indf, writedf["price"] = sor usedf.loc. - Column assignment replaces the column.
df["total"] = ...swaps in a new column. It does not edit an existing array in place. Other Series that you took fromdf["total"]earlier keep the old values. - The
.locform still works for partial updates. Writing todf.loc[mask, "col"]mutatesdfdirectly, so it is not chained. - Reads are cheap. Copying is deferred until a write happens. Removing old defensive
.copy()calls can save memory, but you can keep them without harm.
Debugging an update that did not stick
- Search the line for two sets of square brackets before the
=.df[a][b] = xis the usual sign. - Check for
inplace=Trueon anything that starts fromdf["col"]. - Turn warnings into errors while you test:
import warnings; warnings.simplefilter("error"). The first chained write then raises an exception with a line number. - After the fix, print
dfor assert on the values. Do not trust the absence of a warning alone. Under older pandas, a chained write can fail without any warning.
Exercise
Exercise
The code below runs on pandas 3.0 without an error, but "bonus" in staff stays 0 for every row. Explain why, and rewrite the last line so that senior staff get a bonus of 500.
import pandas as pd
staff = pd.DataFrame({"name": ["Ana", "Ben", "Cy"], "years": [8, 2, 11]})
staff["bonus"] = 0
staff[staff["years"] >= 5]["bonus"] = 500
Show answer
The last line is a chained assignment. staff[staff["years"] >= 5] returns a temporary DataFrame, and ["bonus"] = 500 writes into that temporary object. Under Copy-on-Write the write never reaches staff, and pandas only emits a ChainedAssignmentError warning. The fix is a single .loc call on the original: staff.loc[staff["years"] >= 5, "bonus"] = 500. Ana and Cy then get 500 and Ben stays 0. An equivalent one-line version is staff["bonus"] = np.where(staff["years"] >= 5, 500, 0), which needs import numpy as np.
Exercise
You select recent = orders[orders["year"] == 2026] and then add recent["tax"] = recent["amount"] * 0.2. On pandas 2.2 without CoW this raises SettingWithCopyWarning. Give two ways to remove the warning without changing the result in recent, and say what neither way does to orders.
Show answer
First, create an independent subset with recent = orders[orders["year"] == 2026].copy() and then assign the column. Second, build it in one expression with recent = orders[orders["year"] == 2026].assign(tax=lambda d: d["amount"] * 0.2). In both cases recent gets the new "tax" column and orders is left unchanged, because recent is a separate object.