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"] = .... It explains why some assignments silently do nothing and how to avoid the warnings pandas raises about them.
What chained assignment is
Chained assignment means two indexing steps in a row, where the second step assigns a value. The first step may return a copy of the data, so the assignment changes a temporary object and your DataFrame stays the same.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
})
# Chained: df[mask] runs first, then ["price"] = ... runs on its result
df[df["price"] > 10]["price"] = 0
print(df)The printed frame still has the original prices. In older pandas versions this raised SettingWithCopyWarning. In pandas 3.0, Copy-on-Write is always on, and the assignment has no effect on df.
Use a single indexing step
Do the selection and the assignment in one .loc call. .loc[rows, column] writes directly into df.
df.loc[df["price"] > 10, "price"] = 0
print(df)The same rule applies when you add a new column for some rows only.
df.loc[df["price"] == 0, "flag"] = "free"Rows that do not match get NaN in flag.
Copying a slice you want to modify
A common warning comes from taking a subset and then adding a column to it.
expensive = df[df["price"] > 1]
expensive["tax"] = expensive["price"] * 0.2On older pandas, this may warn that you are setting a value on a copy of a slice. Make your intent explicit with .copy().
expensive = df[df["price"] > 1].copy()
expensive["tax"] = expensive["price"] * 0.2Now expensive is its own DataFrame. Changing it never touches df, and pandas has nothing to warn about.
How to choose
| Goal | Write this |
|---|---|
| Change some rows of an existing column | `df.loc[mask, "col"] = value` |
| Create a column from a subset | `sub = df[mask].copy()`, then `sub["new"] = ...` |
| Build a new frame in a chain | `df.assign(new=...)` |
assign() always returns a new DataFrame, so it avoids the problem. It is a good fit when you do not want to modify the original.
Checking your pandas version
Behavior differs by version, so check yours. Pandas 2.x can enable Copy-on-Write with an option, which lets you test your code early.
import pandas as pd
print(pd.__version__)
pd.options.mode.copy_on_write = TrueWrite code that is correct under both modes: one .loc assignment, or an explicit .copy(). Then the warnings disappear and the results do not depend on the version.
Exercise
This code is meant to set price to 5.0 for every row where qty is below 3, but df does not change. Rewrite the line so it works: df[df["qty"] < 3]["price"] = 5.0
Show answer
Use one .loc call: df.loc[df["qty"] < 3, "price"] = 5.0. The original line indexes twice, and the assignment lands on a temporary result instead of df.
Exercise
You filter a DataFrame into recent and want to add a column to it without changing the original. What should you add to the filtering line?
Show answer
Add .copy(), as in recent = df[mask].copy(). The new column is then added to an independent DataFrame.