Sub topic 3
Dropping Unneeded Defensive Copies in pandas 3
Assume you know how to select rows and columns with .loc and .iloc, and understand basic pandas objects. In pandas 3, Copy-on-Write (CoW) is the only behavior: a DataFrame or Series derived from another object cannot change its parent.
Dropping unneeded defensive copies
In older pandas code, you may see .copy() added after every selection:
subset = df.loc[df["score"] > 0].copy()With CoW, the explicit copy is usually unnecessary when the purpose is only to protect df from later edits:
subset = df.loc[df["score"] > 0]
subset.loc[:, "score"] = 100
print(df["score"].tolist()) # The original values are unchangedThe selected object can initially share data with df. CoW gives it separate storage only when a write requires it.
In-place methods on derived objects
An in-place method on a column or other derived object cannot update its parent:
df["name"].fillna("Unknown", inplace=True)Rewrite the operation as an assignment to the original DataFrame:
df.loc[:, "name"] = df["name"].fillna("Unknown")The right-hand side creates the result. The .loc assignment writes that result directly into df.
Performance and memory effects
CoW avoids copying data that is only read. This can reduce memory use and make selections cheaper. The first write to shared data may allocate memory, so repeated edits to many derived objects can still cost memory. Measure important workloads rather than assuming .copy() is faster.
Migrating code from pandas 2.x
Audit code for:
df["col"][mask] = valueand other chained assignments. Replace them with one.loccall.inplace=Trueondf["col"]or another derived object. Assign the returned result instead.- Writes to arrays from
.to_numpy()or.values. These arrays may be read-only; use.copy()before modifying the array. .copy()calls used only to prevent accidental parent changes. Remove them after testing.
Exercise
How should you rewrite df["price"].replace(0, 1, inplace=True)?
Show answer
Use df.loc[:, "price"] = df["price"].replace(0, 1).