Sub topic 12
Views, copies, and Copy-on-Write
This chapter assumes you know how a DataFrame groups same-dtype columns into blocks. It also assumes you can read NumPy-style indexing. You will learn when pandas shares memory between objects, and how Copy-on-Write (CoW) makes that sharing safe.
Why sharing matters for memory
Copying a large DataFrame doubles its memory use. Pandas avoids this where it can. A view is an object that reads the same underlying array as another object. A copy owns its own array.
Before CoW, whether an operation returned a view or a copy depended on the operation and the dtypes involved. Writing to a view could change the original frame, and writing to a copy could not. That produced the well-known SettingWithCopyWarning.
The Copy-on-Write rule
Copy-on-Write replaces that guesswork with one rule: every DataFrame or Series derived from another behaves as an independent copy. Pandas may still share memory internally. When you write to a shared array, pandas copies it first, and only then modifies it.
CoW is the default in pandas 3.0. In pandas 2.x you turn it on with an option. On 3.0 the option is deprecated and the line below can be removed.
import pandas as pd
pd.options.mode.copy_on_write = True
df = pd.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]})
col = df["a"]
col.iloc[0] = 100
print(df["a"].tolist())
print(col.tolist())The output is [1, 2, 3] and then [100, 2, 3]. Writing to col did not touch df.
Sharing is per block
The copy happens at the level of the blocks from the previous chapters. A shallow copy shares every block. A write copies only the block that holds the modified column.
import numpy as np
import pandas as pd
pd.options.mode.copy_on_write = True
df = pd.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]})
df2 = df.copy(deep=False)
print(np.shares_memory(df["a"].to_numpy(), df2["a"].to_numpy()))
print(np.shares_memory(df["b"].to_numpy(), df2["b"].to_numpy()))
df2.iloc[0, 0] = 100
print(np.shares_memory(df["a"].to_numpy(), df2["a"].to_numpy()))
print(np.shares_memory(df["b"].to_numpy(), df2["b"].to_numpy()))
print(df["a"].tolist())The four checks print True, True, False, True. Then df["a"] prints as [1, 2, 3]. Writing to a copied only the int64 block. The float64 block holding b is still shared, so you pay for one block and not the whole frame.
What changes in your code
| Pattern | Before CoW | Under CoW |
|---|---|---|
| `s = df["a"]; s[0] = 1` | Might change `df`, might warn | Never changes `df` |
| `df[mask]["b"] = 0` (chained assignment) | Often silently did nothing | Never updates `df` |
| `df.loc[mask, "b"] = 0` | Updates `df` | Updates `df` |
| Defensive `.copy()` before writing | Often needed | Usually unnecessary |
Chained assignment means indexing twice and assigning to the result. The first step returns a new object, so the assignment lands on a temporary. Pandas 3.0 warns when it detects this. Assign in one step instead:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]})
df.loc[df["a"] > 1, "b"] = 0.0
print(df)Common errors
- Expecting a write to propagate. Code that relied on
sub = df[...]; sub["x"] = 1updatingdfbreaks under CoW. Assign todfdirectly with.loc. - Adding
.copy()everywhere. It is harmless but wastes memory, because it forces the full copy that CoW would otherwise delay or skip. - Measuring memory too early. A derived frame may share arrays with its source.
memory_usagereports each object's size as if it owned the data, so the sum overstates real usage until writes happen.
Exercise
Under CoW, you run df2 = df.copy(deep=False) on a frame with one int64 column and one object column, then assign a new value to a cell in the int64 column of df2. Which data is copied, and does df change?
Show answer
Only the int64 block is copied, because the write touches it. The object column's array stays shared with df. df does not change, since df2 behaves as an independent object.