Sub topic 12
Views, copies, and Copy-on-Write
The earlier chapters showed that a DataFrame holds its columns in arrays, and that the block manager groups same-dtype columns into shared 2-D arrays. This chapter covers what happens when you derive one object from another. You can end up with two objects over the same memory, or with two separate copies. Which one you get changes your memory use, and it decides whether an assignment reaches the original data.
This chapter assumes you can create a DataFrame, select columns and rows, and assign values with .loc. It also assumes you know that a NumPy array is a contiguous buffer. The chapter relies on the block manager idea from the previous chapters.
Views and copies
A view is a new pandas or NumPy object that reads the same underlying buffer as another object. Writing through one object changes the data the other one sees. A copy has its own buffer, so writes stay separate.
NumPy already works this way. A basic slice is a view, and fancy indexing makes a copy:
import numpy as np
a = np.arange(6)
view = a[1:4]
copy = a[[1, 2, 3]]
view[0] = 100
print(a) # [ 0 100 2 3 4 5]
print(np.shares_memory(a, view)) # True
print(np.shares_memory(a, copy)) # FalseClassic pandas inherited this behavior, but the rules were harder to predict. Whether df[...] returned a view or a copy depended on the indexer and on the block layout behind the frame. Those rules were never a stable part of the API.
Why the old behavior was unpredictable
Recall that columns of the same dtype are consolidated into one 2-D block. Two things followed from that layout:
- Selecting one column from a single-dtype frame could return a view into the shared block.
- Selecting rows with a boolean mask or a list of labels always had to build a new array, so it returned a copy.
- Selecting from a frame with mixed dtypes might copy or not, depending on how many blocks the selection touched.
You could not tell from the code whether a write would reach the original frame. Pandas tried to warn you with SettingWithCopyWarning, but the warning was a heuristic. It missed some bugs and flagged code that was correct.
The classic failing pattern is chained assignment. It indexes twice, then assigns:
df[df["a"] > 1]["b"] = 0 # may write to a temporary copy, not to dfThe first indexing step returns a temporary object. The second step writes into that temporary. Whether df changes depends on whether the temporary happened to be a view.
The Copy-on-Write rule
Copy-on-Write (CoW) replaces those layout-dependent rules with one rule:
> Any object derived from another DataFrame or Series behaves as an independent copy. Modifying it never changes the original, and modifying the original never changes it.
You can reason about your code without knowing about blocks. The rule is a promise about behavior. Pandas may still share memory underneath, and it copies only at the moment one of the objects is written to. That deferred copy is the "copy on write".
CoW is opt-in in pandas 2.x and the only behavior in pandas 3.0 and later. On 2.x, enable it at the top of your program:
import pandas as pd
pd.options.mode.copy_on_write = True # needed on 2.x; always on in 3.0+On 3.0 and later this option is deprecated, and you can leave the line out.
A derived object does not write back
import pandas as pd
pd.options.mode.copy_on_write = True # omit on pandas 3.0+
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]) # 1Without CoW, a single-dtype frame could print 100 for the last line, because col was a view. With CoW it always prints 1.
Lazy copies share memory until a write
Methods that return a new object, such as reset_index(drop=True), do not copy the data right away. The new frame points at the same arrays. The data is copied only when one side is modified.
import numpy as np
import pandas as pd
pd.options.mode.copy_on_write = True # omit on pandas 3.0+
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df2 = df.reset_index(drop=True)
print(np.shares_memory(df["a"].to_numpy(), df2["a"].to_numpy())) # True
df2.loc[0, "a"] = 99
print(np.shares_memory(df["a"].to_numpy(), df2["a"].to_numpy())) # False
print(df["a"].tolist()) # [1, 2, 3]
print(df2["a"].tolist()) # [99, 2, 3]The first write to df2 triggers the copy. Pandas tracks which objects reference a block, so it only copies when a block is actually shared. If you write to a frame that nobody else references, nothing is copied and the write happens in place.
Chained assignment no longer works
Under CoW the second indexing step in a chain acts on a temporary object, so the assignment cannot reach df. Pandas raises a warning (ChainedAssignmentError) when it detects the pattern. The temporary is never written back, which means the code does nothing.
Do the selection and the assignment in a single .loc call:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
# Wrong: the assignment goes to a temporary and is lost.
# df[df["a"] > 1]["b"] = 0
# Right: one indexing operation that selects rows and column, then assigns.
df.loc[df["a"] > 1, "b"] = 0
print(df)The output is:
a b
0 1 4
1 2 0
2 3 0The same applies to in-place methods called on a selection. df["b"].fillna(0, inplace=True) modifies a temporary Series and leaves df unchanged. Write df["b"] = df["b"].fillna(0) instead.
NumPy arrays you get from pandas are read-only
to_numpy() and .values can return an array that shares memory with the frame. If you could write to it, you would change the frame behind CoW's back. To prevent that, pandas returns a read-only view when the memory is shared.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy()
try:
arr[0] = 5
except ValueError as e:
print(e) # assignment destination is read-only
writable = df["a"].to_numpy().copy()
writable[0] = 5
print(writable, df["a"].tolist()) # [5 2 3] [1, 2, 3]If you need to mutate the values, call .copy() on the array or use np.array(...). This is the one place where CoW can surface as an error in older code.
What CoW changes about memory
Before CoW, defensive copies were common. Many methods had a copy= argument, and users often called df.copy() just to be safe. Under CoW the safety comes from the rule itself, so you can skip those calls and pay for a copy only when you modify something.
Some consequences for memory:
- Chains such as
df.rename(...).set_index(...)no longer copy all the data at each step. They share arrays until one is written to. - A selection of whole columns, such as
df[["a", "b"]], can share arrays with the source instead of copying them. - The first write to a shared block copies that whole block. Because the block manager groups same-dtype columns, writing to one column of a consolidated block can copy more than that column.
- In pandas 3.0, the
DataFrameandSeriesconstructors copy NumPy input arrays by default, so modifying the array afterward does not change the frame.
memory_usage() does not account for sharing. Two frames that share arrays each report the full size, so adding their numbers overstates what the process uses. To measure real use, check the process's memory with an operating system tool or a profiler.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Assignment on `df[mask]["b"]` has no effect | Chained assignment writes to a temporary | Use `df.loc[mask, "b"] = value` |
| `df["b"].fillna(0, inplace=True)` leaves `df` unchanged | In-place method on a temporary Series | Assign the result: `df["b"] = df["b"].fillna(0)` |
| `ValueError: assignment destination is read-only` | `to_numpy()` returned a read-only view | Copy the array before writing |
| Changing a derived frame was expected to change the original | Code relied on old view behavior | Assign into the original with `.loc`, or reassign the variable |
| Total of `memory_usage()` across frames exceeds process memory | Frames share arrays | Measure process memory instead |
| `SettingWithCopyWarning` appears | CoW is not enabled on pandas 2.x | Enable CoW, or upgrade to 3.0 |
Moving old code to CoW
On pandas 2.x, you can find affected code before upgrading. Turn on the option and run your tests. A second mode, pd.options.mode.copy_on_write = "warn", emits a warning at each place where behavior will differ under CoW. Fix the warnings, then enable CoW.
Typical fixes are mechanical:
- Replace chained assignment with a single
.locassignment. - Replace
inplace=Truecalls on selections with reassignment. - Remove
.copy()calls that only guarded against accidental writes. - Copy NumPy arrays before mutating them.
Exercise
The code below runs on pandas 3.0. Predict what it prints, and explain why df is or is not changed.
import pandas as pd
df = pd.DataFrame({"x": [10, 20, 30], "y": [1, 2, 3]})
sub = df[df["x"] > 10]
sub.loc[sub.index[0], "y"] = 99
print(df["y"].tolist())
print(sub["y"].tolist())
Show answer
It prints [1, 2, 3] and then [99, 3]. The boolean mask builds a new frame in sub, and under Copy-on-Write that frame is independent of df. The write to sub copies the data it needs and leaves df untouched. To change df, assign with df.loc[df["x"] > 10, "y"] = 99.
Exercise
A colleague writes df["score"].fillna(0, inplace=True) and finds that df still has missing values under Copy-on-Write. Why, and what is the fix?
Show answer
df["score"] returns a derived Series, and inplace=True modifies only that Series. Under Copy-on-Write the change does not write back to df. Write df["score"] = df["score"].fillna(0) so the result is assigned into the frame.
Exercise
You build df2 = df.reset_index(drop=True) on a 2 GB frame and call memory_usage(deep=True).sum() on both frames. The total is about 4 GB. Does the process use 4 GB? What happens to memory after df2.loc[0, "a"] = 1?
Show answer
No. Under Copy-on-Write the two frames share the same arrays, so the process uses about 2 GB, and memory_usage reports the full size for each frame because it does not account for sharing. After the write, pandas copies the block that holds column a for df2. Memory grows by the size of that block, which can be more than one column if a shares a consolidated block with others.