Sub topic 2
The one rule of Copy-on-Write
This chapter assumes you know how to create DataFrames and Series, select columns and rows, and use .loc and .iloc. It also assumes you know that Python variables are references to objects. NumPy knowledge helps but is not required.
The rule
pandas 3 has one rule for modifying data:
Any DataFrame or Series derived from another object behaves as an independent copy. Modifying it never changes the object it came from, and modifying the original never changes it.
"Derived" covers almost everything that returns a new pandas object: selecting a column, slicing rows, picking several columns, reset_index(), rename(), head() and so on. The result is yours to change, and the parent stays as it was.
This is Copy-on-Write (CoW). In pandas 3 it is the only behavior. There is no option to turn it off.
Changing a derived object
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
col = df["a"]
col.iloc[0] = 100
print(col.iloc[0]) # 100
print(df["a"].iloc[0]) # 1, df is unchangedcol came from df, so writing to col changes only col. In pandas 2.x, whether this also changed df depended on internal details such as column dtypes and how the block was stored. In pandas 3 the answer is always the same.
Changing the parent
The rule works in both directions. A derived object does not see later changes to its parent:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
subset = df[["a"]]
df.loc[1, "a"] = 200
print(df["a"].tolist()) # [1, 200, 3]
print(subset["a"].tolist()) # [1, 2, 3], subset kept its own valuesThink of subset as a snapshot taken at the moment you created it.
What the rule does not cover
The rule applies to derived objects. Plain Python assignment does not derive anything. It adds a second name for the same object:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
alias = df
alias.loc[0, "a"] = 100
print(df["a"].iloc[0]) # 100, alias and df are the same object
print(alias is df) # TrueWriting to a DataFrame changes that DataFrame. CoW only guarantees that other objects built from it stay unaffected. If you want a separate object, derive one, for example with df.copy().
Predicting outcomes
Apply the rule by asking one question: did the object I am writing to come from another object, or is it the object I want to change?
| Code | Effect on `df` |
|---|---|
| `df.loc[0, "a"] = 1` | Changes `df`. You write to `df` itself. |
| `col = df["a"]; col.iloc[0] = 1` | No change. `col` is derived. |
| `part = df.head(2); part.loc[0, "a"] = 1` | No change. `part` is derived. |
| `alias = df; alias.loc[0, "a"] = 1` | Changes `df`. `alias` is `df`. |
| `df["a"][0] = 1` | No change. `df["a"]` is a temporary derived object. |
The last row is chained assignment. It looks like it writes to df, but the first step, df["a"], creates a derived Series, and the write lands there. Chapter 4 covers this and the warning it raises. For now, remember that the rule explains why it stops working.
Why this is better than before
Before pandas 3, the same code could modify the original or not, depending on whether pandas had returned a view (shared memory) or a copy. You could not tell by reading the code, and SettingWithCopyWarning only caught some cases. Code could pass tests on one dataset and silently corrupt data on another.
With CoW you can read a function and know what it does to its inputs. A function that receives a DataFrame and modifies only objects it derived cannot change the caller's data.
Fixing a common habit
A lot of older code protects the caller's data like this:
def add_flag(df):
df = df.copy() # defensive copy
df["flag"] = df["a"] > 1
return dfUnder CoW, the .copy() is not needed here. df["flag"] = ... on a derived object cannot affect the caller. Chapter 7 covers when a copy is still needed.
Exercise
Given df = pd.DataFrame({"x": [1, 2, 3]}) and s = df["x"], what are s.iloc[0] and df["x"].iloc[0] after running df.loc[0, "x"] = 99? Then, what are they if you instead run s.iloc[0] = 99?
Show answer
After df.loc[0, "x"] = 99, s.iloc[0] is 1 and df["x"].iloc[0] is 99. s was derived from df, so it is unaffected by writes to df. After s.iloc[0] = 99 instead, s.iloc[0] is 99 and df["x"].iloc[0] stays 1, because writes to a derived object never reach its parent.