Sub topic 2
Why Chained Assignment Stops Working
Assume you know how to create pandas DataFrames and use .loc and .iloc. In pandas 3, Copy-on-Write (CoW) is the only behavior. Its rule is simple: a DataFrame or Series derived from another object cannot change the object it came from.
Why chained assignment stops working
Chained assignment selects data in multiple steps:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df["a"][0] = 100
print(df["a"].iloc[0]) # 1df["a"] creates a derived Series. The second operation assigns to that Series, not directly to df. Under CoW, the assignment cannot update the original DataFrame. pandas reports a ChainedAssignmentError warning because the operation can never do what the code appears to request.
Use one indexing operation instead:
df.loc[0, "a"] = 100
print(df["a"].iloc[0]) # 100For several rows, put the condition and target column in the same .loc call:
df.loc[df["a"] > 1, "b"] = 100Lazy copies: how pandas shares data until you write
CoW does not necessarily copy all data when you derive an object. pandas can initially let the original and derived objects share memory. When either object is written to, pandas makes the copy needed to protect the other object. This is a lazy copy: the cost happens at the first write.
flowchart TD
A["df"] --> B["Derived Series"]
A -. "shared data initially" .-> B
B --> C["Write to Series"]
C --> D["Copy before write"]
D --> E["df remains unchanged"]This design can reduce memory use for read-only selections. Treat the sharing as an implementation detail. Always write through the object you intend to change.
> callout note > CoW protects object independence, but it does not make chained assignment valid. Use .loc or .iloc for assignments.
Read-only arrays from `to_numpy()` and `.values`
Arrays returned from a pandas object may expose shared pandas data. With CoW, such arrays can be read-only:
arr = df["a"].to_numpy()
print(arr.flags.writeable) # False
arr = df["a"].to_numpy().copy()
arr[0] = 200The explicit NumPy copy is appropriate when you need to mutate the array. That mutation affects neither df nor its Series.
Exercise
How should you update column b to 0 wherever column a is greater than 10?
Show answer
Use df.loc[df["a"] > 10, "b"] = 0.