Sub topic 2
The One Rule of Copy-on-Write
This chapter assumes you can create DataFrames and Series and select with .loc and .iloc. It also assumes you know that Python variables are references to objects, and that a mutable object can be changed through any reference to it. NumPy knowledge helps but is not needed here.
The rule
pandas 3 has one behavior for modifications, called Copy-on-Write (CoW):
Any DataFrame or Series that is derived from another object behaves as an independent copy. Changing the derived object never changes the object it came from.
Every other CoW behavior follows from this sentence. There is no option to turn it off and no "sometimes a view" case left. A derived object is what you get back from an operation like selecting a column, slicing rows, filtering, renaming, or resetting the index.
The rule is about what you can observe. It does not promise that pandas copies memory at every step. Internally, pandas shares data between objects and copies only when one of them is written to. The chapter on lazy copies covers that mechanism. Here you only need the observable guarantee.
The rule in action
Take a column out of a DataFrame and modify it:
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 is derived from df, so writing to col changes only col. In pandas 2.x and earlier, the same code could change df as well. That depended on internal details you could not see from the code. The next chapters cover how that ambiguity worked and what to do about it. Under CoW the answer is the same every time.
The rule also works in the other direction
The guarantee is symmetric. If you change the parent after deriving an object, the derived object does not change either:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
col = df["a"]
df.loc[0, "a"] = 100
print(df["a"].iloc[0]) # 100
print(col.iloc[0]) # 1, col keeps the values it had when it was createdThink of col as a snapshot taken at the moment of derivation. Later edits to df do not leak into it. This removes a common source of bugs, where a variable you set aside earlier silently changed because some other code edited the original.
What counts as a derived object
A derived object is the result of an operation on another pandas object. The rule applies to all of these, whether the result is a Series or a DataFrame:
| Operation | Example | Changing the result affects the original? |
|---|---|---|
| Select a column | `df["a"]` | No |
| Select several columns | `df[["a", "b"]]` | No |
| Slice rows by position | `df.iloc[:2]` | No |
| Filter with a boolean mask | `df[df["a"] > 1]` | No |
| Rename or reset the index | `df.rename(...)`, `df.reset_index(drop=True)` | No |
| Take the first rows | `df.head(2)` | No |
| Explicit copy | `df.copy()` | No |
The following example applies the same write to each kind of derived object and then checks that df never changed:
import pandas as pd
def poke(obj):
"""Overwrite the first value of a Series or DataFrame with -1."""
if isinstance(obj, pd.Series):
obj.iloc[0] = -1
else:
obj.iloc[0, 0] = -1
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
derived = {
"column": df["a"],
"column list": df[["a"]],
"row slice": df.iloc[:2],
"filtered": df[df["a"] > 1],
"renamed": df.rename(columns={"a": "x"}),
"reset index": df.reset_index(drop=True),
"head": df.head(2),
"copy": df.copy(),
}
for name, obj in derived.items():
poke(obj)
print(df["a"].tolist()) # [1, 2, 3]
print(df["b"].tolist()) # [4, 5, 6]In pandas 2.x, some of these cases (the column, the slice, head) could write through to df and some could not. Code like this also raised SettingWithCopyWarning in various places. That warning is gone in pandas 3 because the situation it described no longer exists.
What the rule does not cover: the same object
The rule talks about objects that are derived from another object. It says nothing about two names that point to the same object. Plain assignment with = does not derive anything. It adds a second name for the object you already have:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
same = df # a second name for the same object, not a derived object
same.loc[0, "a"] = 100
print(df["a"].iloc[0]) # 100, df and same are one object
print(same is df) # TrueThe same applies to function arguments. A function receives a reference to the object you pass in, so modifying it inside the function modifies the caller's object:
import pandas as pd
def add_total(frame):
frame["total"] = frame["a"] + frame["b"]
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
add_total(df)
print(list(df.columns)) # ['a', 'b', 'total']This is ordinary Python behavior for mutable objects, and CoW does not change it. If you want a function to leave the caller's data alone, have it return a new object instead of modifying its argument:
import pandas as pd
def with_total(frame):
return frame.assign(total=frame["a"] + frame["b"])
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
out = with_total(df)
print(list(df.columns)) # ['a', 'b']
print(list(out.columns)) # ['a', 'b', 'total']assign returns a derived DataFrame, so the rule guarantees that df is not affected.
Writing to the original still works
CoW does not make DataFrames immutable. You can still modify an object that you hold directly, and the change is visible through every name that refers to it. The following writes all change df itself:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
df.loc[df["foo"] > 1, "bar"] = 100
print(df)The result is that bar becomes [4, 100, 100]. The write goes through df in one .loc call, so df is the object being modified. The next chapter looks at which assignment forms work this way and which ones modify only a temporary object.
Predicting the outcome of a modification
For any line that modifies data, you can predict its effect with two questions:
- Which object is being written to? Find the object at the left of the write: the variable in
x.loc[...] = ...,x.iloc[...] = ..., orx[...] = .... - Where did that object come from? If it is the object you started with, the write changes it, and every other name for the same object sees the change. If an operation produced it, the write changes only that object.
Apply this to a few cases. Assume df is a DataFrame you built directly.
| Code | Object written to | Effect on `df` |
|---|---|---|
| `df.loc[0, "a"] = 1` | `df` | Changed |
| `s = df["a"]` then `s.iloc[0] = 1` | `s` (derived) | None |
| `d2 = df` then `d2.loc[0, "a"] = 1` | `d2`, the same object as `df` | Changed |
| `d3 = df.copy()` then `d3.loc[0, "a"] = 1` | `d3` (derived) | None |
| `df["a"][0] = 1` | A temporary Series from `df["a"]` | None |
The last row is chained assignment. The temporary Series is a derived object, so the write cannot reach df. pandas 3 warns you about this pattern with a ChainedAssignmentError. A later chapter covers it in detail.
Edge cases
Containers that hold Python objects
CoW governs the pandas structures. It does not recursively copy Python objects stored inside them. A copy of a DataFrame is a new DataFrame, but a list stored in a cell is still the same list:
import pandas as pd
df = pd.DataFrame({"tags": [["x"], ["y"]]})
other = df.copy()
other.loc[0, "tags"].append("z") # mutates the list object itself
print(df.loc[0, "tags"]) # ['x', 'z'], the list is sharedThe write here is not a write to the DataFrame. It is a call to list.append on an object that both DataFrames reference, so pandas never sees it. If you store mutable Python objects in cells, this is the one place where changes can still travel between a derived object and its source. Prefer immutable values such as tuples, or copy the inner objects yourself.
NumPy arrays passed to constructors
When you build a Series or DataFrame from a NumPy array, pandas 3 copies the array by default. Later changes to the array do not show up in the pandas object, which keeps the rule consistent:
import numpy as np
import pandas as pd
arr = np.array([1, 2, 3])
s = pd.Series(arr)
arr[0] = 100
print(s.iloc[0]) # 1, the Series has its own dataYou can ask for the old sharing behavior with copy=False in the constructor. In that case you are opting out of independence, and it is your job to avoid modifying the array.
Arrays you get back from pandas
The rule has a counterpart for the other direction. A NumPy array that exposes the data of a Series or DataFrame, such as the result of to_numpy(), must not become a back door for modifying a pandas object. pandas returns such arrays as read-only. Handling them gets its own chapter.
Common mistakes
- Expecting a derived object to track later changes.
col = df["a"]is a snapshot. If you want to see updates, select again fromdfor work ondfdirectly. - Treating
=as a copy.df2 = dfdoes not derive anything. Usedf.copy()or an operation that returns a new object when you want independence. - Modifying a function argument by accident. A function that assigns into its argument changes the caller's object. Return a new object if that is not what you want.
- Writing
.copy()everywhere "to be safe". Under CoW, derived objects are already independent, so a.copy()placed just to prevent write-through usually does nothing useful. A later chapter covers the few cases where an explicit copy is still the right tool. - Assuming the rule protects objects inside cells. Lists, dicts, and other mutable values stored in cells are shared, as shown above.
Why a single rule helps
Before pandas 3, whether a modification propagated depended on the operation, the dtypes of the columns, and whether the data was stored in one block or several. Two lines that looked alike could behave differently, and code could change behavior when a pandas release changed an internal detail. With CoW you reason about objects and where they came from, not about memory layout. That makes code easier to read, and it means a result you verify today stays valid after an upgrade within pandas 3.
Exercise
What does this code print, and why? import pandas as pd df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) sub = df[df["a"] > 1] view = df sub.loc[sub.index[0], "b"] = 0 view.loc[0, "a"] = 10 print(df["a"].tolist(), df["b"].tolist()) print(sub["b"].tolist())
Show answer
It prints [10, 2, 3] [4, 5, 6] and then [0, 6]. The variable sub is derived from df through a filter, so writing to sub changes only sub (its b values become [0, 6]) and leaves df["b"] as [4, 5, 6]. The variable view is a second name for df, not a derived object, so writing through view changes df, and df["a"] becomes [10, 2, 3].
Exercise
A function normalizes a column of the DataFrame passed to it by writing frame["score"] = frame["score"] / frame["score"].max(). After calling it, the caller's DataFrame has changed, and the caller did not want that. Does Copy-on-Write explain this or prevent it, and how would you change the function?
Show answer
Copy-on-Write does not prevent it. The function receives a reference to the caller's object, so frame is the same object, not a derived one, and writing to it changes the caller's data. Change the function to return a new object, for example return frame.assign(score=frame["score"] / frame["score"].max()), and have the caller use the returned DataFrame. The result of assign is a derived object, so the original stays unchanged.
Exercise
You store a list in each cell of an object column, copy the DataFrame with df.copy(), and call append on a list taken from the copy. The original DataFrame's list also changed. Why does this not break the Copy-on-Write rule?
Show answer
The rule covers pandas objects, and the copy is a separate DataFrame. The append call changes the list object itself, which both DataFrames reference, and pandas is not involved in that modification. To avoid it, store immutable values such as tuples, or copy the inner lists yourself.