Sub topic 13
Copies, views, and avoiding chained assignment
This chapter assumes you can select with [], loc, and iloc, filter with boolean masks, and add columns with assignment. You should also know that a Python name is a reference to an object, not the object itself. Here you will learn when pandas shares data between objects, when it copies, and why some assignments silently do nothing.
Two meanings of "the same data"
A view is an object that reads the same memory as another object. Writing through a view changes the original. A copy owns its own memory, so writing to it leaves the original alone.
Older pandas (before 3.0) did not make this predictable. Whether a slice came back as a view or a copy depended on the index type, the dtypes, and the selection method. That uncertainty produced SettingWithCopyWarning.
pandas 3.0 removes the uncertainty with Copy-on-Write (CoW). Under CoW:
- Every selection behaves as if it were a new, independent object.
- pandas may share memory internally, but it copies the data the moment either object is modified.
- You can never change a parent by modifying something derived from it.
pandas 2.x lets you opt in to this behavior. This tutorial writes code that is correct under both models.
import pandas as pd
print(pd.__version__)Names are not copies
Assigning a DataFrame to a second name creates no new data. Both names point to one object.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima"], "pop_m": [0.7, 10.7]})
alias = df
alias.loc[0, "pop_m"] = 0.8
print(df["pop_m"].tolist()) # [0.8, 10.7]; same object, so df changedThis is ordinary Python behavior, and CoW does not change it. CoW only governs objects that pandas derives from another object, such as slices, filtered frames, and results of methods like rename. When you want an independent object, call .copy().
import pandas as pd
a = pd.Series([1, 2, 3])
b = a.copy()
b.iloc[0] = 99
print(a.tolist()) # [1, 2, 3]
print(b.tolist()) # [99, 2, 3].copy() is deep by default. It copies the data, not only the container.
What chained assignment is
Chained assignment is an assignment where the target comes from two or more indexing operations in a row:
df[df["pop_m"] > 3]["pop_m"] = 0Python runs this as two separate calls:
df[df["pop_m"] > 3]calls__getitem__and returns an intermediate object.["pop_m"] = 0calls__setitem__on that intermediate object.
A boolean mask always produces a copy, so step 2 writes into a temporary frame that is then thrown away. The original df is untouched.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
df[df["pop_m"] > 3]["pop_m"] = 0 # chained: writes to a temporary copy
print(df["pop_m"].tolist()) # [0.7, 10.7, 3.1, 2.8] nothing changedpandas 2.x usually warns with SettingWithCopyWarning. pandas 3.0 warns with ChainedAssignmentError. In both versions the write is lost.
The fix is a single loc call. It receives the row selector and the column together, so it can write into the original object.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
df.loc[df["pop_m"] > 3, "pop_m"] = 0
print(df["pop_m"].tolist()) # [0.7, 0.0, 0.0, 2.8]Common chained patterns
Chaining is not always obvious. Each of these has the same problem.
| Pattern | Problem | Safe replacement |
|---|---|---|
| `df[mask]["col"] = v` | Writes to a filtered copy | `df.loc[mask, "col"] = v` |
| `df["col"][mask] = v` | Writes to an intermediate Series | `df.loc[mask, "col"] = v` |
| `df.loc[mask]["col"] = v` | `loc[mask]` returns a copy before the second step | `df.loc[mask, "col"] = v` |
| `df.iloc[0]["col"] = v` | A row selection can be a copy | `df.loc[df.index[0], "col"] = v` |
| `sub = df[mask]; sub["x"] = 1` | Writes to a derived frame, often with a warning | `sub = df[mask].copy()` first |
The second row, df["col"][mask] = v, used to work in many cases because a column selection was often a view. Under CoW it stops working, so convert it everywhere.
Working on a subset deliberately
Often you do want a separate frame to modify, for example a filtered table that you will enrich with new columns. Call .copy() at the point where you create it. This tells both pandas and the next reader that the subset is independent.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
big = df[df["pop_m"] > 3].copy()
big["rank"] = big["pop_m"].rank(ascending=False)
print(big)
print("rank" in df.columns) # False; df is unaffectedWithout .copy(), pandas 2.x may raise SettingWithCopyWarning on the big["rank"] line. The warning can appear even when your code is correct, because pandas cannot always tell. Adding .copy() removes both the warning and the doubt.
Enabling Copy-on-Write in pandas 2.x
On pandas 2.x you can turn CoW on for the whole process. Set the option before you create any objects.
import pandas as pd
pd.options.mode.copy_on_write = True # not needed in pandas 3.0
s = pd.Series([1, 2, 3])
t = s[:2]
t.iloc[0] = 99
print(s.tolist()) # [1, 2, 3]; modifying t never changes s
print(t.tolist()) # [99, 2]CoW has these effects:
- Predictability. A derived object is always independent, so you stop asking whether a slice is a view or a copy.
- Fewer eager copies. Methods such as
renameorreset_indexcan share memory until a write occurs, which saves memory and time. - Chained assignment stops working entirely. The intermediate object is always a separate object, so the write never reaches the parent. pandas warns about it.
The pandas 3.0 behavior makes inplace=True less useful as well. Methods like df.dropna(inplace=True) still work, but they give no performance advantage over df = df.dropna(). Prefer reassignment, which also lets you chain methods fluently.
Modifying inside functions
Passing a DataFrame to a function passes a reference. In pandas 2.x without CoW, a function that does df["x"] = 1 mutates the caller's frame. Under CoW, column assignment on the argument still mutates the argument, because it modifies that object directly. Slices and derived objects are the ones that stay independent.
If a function should not alter its input, copy first or build a new frame:
import pandas as pd
def add_density(frame: pd.DataFrame) -> pd.DataFrame:
return frame.assign(density=frame["pop_m"] / 10)
df = pd.DataFrame({"pop_m": [1.0, 2.0]})
out = add_density(df)
print("density" in df.columns) # False
print("density" in out.columns) # Trueassign returns a new frame, so the caller's object is never touched.
Checklist
- Write every conditional update as
df.loc[row_selector, column] = value. - Call
.copy()when you filter a frame and plan to modify the result. - Use
assignor reassignment instead ofinplace=True. - Treat any
SettingWithCopyWarningorChainedAssignmentErroras a real bug, not as noise. - Test on pandas 3.0 behavior by enabling
copy_on_writein 2.x.
Exercise
A colleague writes df[df["region"] == "EU"]["pop_m"] = df["pop_m"] * 2 to double the population for EU rows, and the values do not change. Explain why, and write the corrected line.
Show answer
The expression is a chained assignment. df[df["region"] == "EU"] creates a filtered copy, and ["pop_m"] = ... writes into that temporary copy, which is then discarded, so df is unchanged. The corrected line is df.loc[df["region"] == "EU", "pop_m"] *= 2, which selects the rows and the column in one loc call and writes into df itself.
Exercise
You filter a frame with sub = df[df["pop_m"] > 1] and then add sub["tag"] = "large". Which change makes your intent clear and avoids the warning in pandas 2.x, and why does df stay unchanged afterwards?
Show answer
Create the subset with sub = df[df["pop_m"] > 1].copy(). Boolean filtering already returns a new object, so df does not gain the tag column. The explicit .copy() tells pandas that sub is independent, which removes the warning and states the intent.