Sub topic 7
Dropping unneeded defensive copies
This chapter assumes you know .loc and .iloc, the Copy-on-Write (CoW) rule that a derived object never changes its parent, and the idea of lazy copies. It shows which .copy() calls you can delete from pandas 2.x code, and which ones you should keep.
Why defensive copies existed
Before pandas 3, many operations returned a view or a copy depending on internal details. A view shares memory with its parent, so a write through it could change the parent. To avoid that risk, people wrote .copy() after almost every selection. These calls are called defensive copies.
# pandas 2.x habit
subset = df[df["score"] > 50].copy()
subset["passed"] = TrueThe copy silenced the SettingWithCopyWarning and made sure df stayed intact.
What changes under Copy-on-Write
In pandas 3, every derived object behaves as an independent copy. Writing to subset can never change df. The protection that .copy() provided is now built in. The actual data is shared until the first write, so you also don't pay for a copy up front.
This means a defensive copy does two things you usually don't want:
- It copies all the data immediately, even if you never write to the result.
- It adds noise that suggests a hidden view-or-copy risk that no longer exists.
import pandas as pd
df = pd.DataFrame({"score": [40, 60, 80], "name": ["a", "b", "c"]})
subset = df[df["score"] > 50] # no .copy() needed
subset.loc[subset.index[0], "score"] = 0
print(df["score"].tolist()) # [40, 60, 80], df is unchanged
print(subset["score"].tolist()) # [0, 80]The write to subset triggers a copy of only the data that subset needs. df stays as it was.
Common patterns you can simplify
| pandas 2.x code | pandas 3 code |
|---|---|
| `df2 = df.copy(); df2["x"] = 1` | `df2 = df.assign(x=1)` or `df2 = df[:]` then assign |
| `sub = df[df["a"] > 1].copy()` | `sub = df[df["a"] > 1]` |
| `col = df["a"].copy()` | `col = df["a"]` |
| `out = df.reset_index(drop=True).copy()` | `out = df.reset_index(drop=True)` |
| `def f(d): d = d.copy(); d["y"] = 0; return d` | `def f(d): d = d.assign(y=0); return d` |
The last row matters for functions. Under CoW, a function that receives a DataFrame cannot change the caller's object through a derived result. Writing d["y"] = 0 on the argument itself does still modify the caller's d, because d is the same object. Use assign, or make a shallow derived object first, when you want to avoid that.
import pandas as pd
def add_flag(d: pd.DataFrame) -> pd.DataFrame:
return d.assign(flag=True) # returns a new object, input untouched
df = pd.DataFrame({"a": [1, 2, 3]})
out = add_flag(df)
print("flag" in df.columns) # False
print("flag" in out.columns) # TrueWhen you still need `.copy()`
Keep an explicit copy in these cases:
- Writable NumPy arrays.
to_numpy()and.valuesreturn read-only arrays under CoW. To modify the array, call.copy()on it, as indf["a"].to_numpy().copy(). - Snapshots of mutable Python objects stored in cells. CoW protects the pandas data structure. It does not deep-copy lists or dicts that live inside object columns. If you store a list in a cell and mutate it, every holder of that list sees the change.
- Handing data to code outside pandas that expects an independent, writable buffer.
import pandas as pd
df = pd.DataFrame({"tags": [["x"], ["y"]]})
other = df.copy() # copies the container, not the inner lists
other.loc[0, "tags"].append("z")
print(df.loc[0, "tags"]) # ['x', 'z'], the inner list is sharedIf you need full independence for nested objects, use copy.deepcopy on the values. A plain DataFrame.copy(deep=True) does not copy Python objects inside cells.
How to clean up a codebase
- Search for
.copy()calls that directly follow a selection, filter,reset_index,rename,drop, or similar method. - Remove one at a time and run your tests. Behavior should not change, because the result was already independent.
- Keep the copies that fall into the three categories above.
- Watch memory use on large frames. Removing a copy that happened before a read-only step is a real saving. Removing one before a step that writes gives no saving, since the write triggers a copy anyway.
Exercise
A colleague's code reads top = df.nlargest(10, "score").copy() and then only prints top. Is the .copy() needed in pandas 3? What if the next line were top.loc[:, "rank"] = range(1, 11)?
Show answer
In neither case is it needed for protecting df. The result of nlargest is a derived object, so under Copy-on-Write any write to top leaves df unchanged. In the print-only case, the copy only wastes time and memory. In the write case, pandas copies the data on that write, so the explicit copy is redundant there too.
Exercise
Why does arr = df["a"].to_numpy(); arr[0] = 5 fail in pandas 3, and how do you fix it without changing df?
Show answer
Under Copy-on-Write the array that exposes pandas data is read-only, so assigning to it raises an error. Take an explicit copy first: arr = df["a"].to_numpy().copy(). The write then affects only the new array, and df is unchanged.