Sub topic 5
Lazy copies: how pandas shares data until you write
This chapter assumes you know the Copy-on-Write rule from the earlier chapters: a DataFrame or Series derived from another object never changes the object it came from. You should also be comfortable with .loc, .iloc, and with Python objects that hold references to the same underlying data. Basic NumPy knowledge helps. The code needs pandas 3 and NumPy.
The rule says derived objects behave like copies. Copying every derived object right away would be slow and would use a lot of memory, so pandas copies lazily. This chapter covers how that works, which operations share data, when the copy happens, and where the laziness shows up in practice.
Behavior versus implementation
Two statements describe Copy-on-Write, and they sit at different levels.
- Behavior (the guarantee): modifying a derived object never changes its parent, and modifying a parent never changes objects derived from it.
- Implementation (an optimization): pandas lets the parent and the derived object point at the same memory until one of them is written to. Then the written object gets its own copy.
You can rely on the first statement. The second is a mechanism that can change between pandas versions. Code that depends on whether two objects currently share memory is fragile. Code that depends only on the rule is safe.
Sharing until the first write
This example uses np.shares_memory to look at the implementation. You will rarely do this in real code. It is useful here because it makes the hidden state visible.
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
df2 = df.reset_index(drop=True)
print(np.shares_memory(df["a"].to_numpy(), df2["a"].to_numpy())) # True, data is shared
df2.loc[0, "a"] = 100 # the copy happens here, on write
print(np.shares_memory(df["a"].to_numpy(), df2["a"].to_numpy())) # False
print(df["a"].tolist()) # [1, 2, 3]reset_index(drop=True) changes only the index. The values in column a are the same, so pandas builds a new DataFrame object that points at the same array. No data is copied at that point. The first write through df2 finds that its array is also used by another object, so it copies the array first and then writes into the copy. df keeps the original array and never sees the change.
The diagram shows the three stages.
How pandas knows the data is shared
Each block of data inside a DataFrame carries a record of the other objects that use the same memory. This is reference tracking. When you derive a new object lazily, pandas adds it to that record. Before any in-place write, pandas checks the record:
- If no other live object uses the data, the write goes straight into the existing array.
- If another object uses it, pandas copies the data for the object being written, writes into the copy, and updates the records.
Two details follow from this design.
- The record holds weak references. When a derived object is garbage collected, for example because a function returned and its local variables vanished, it drops out of the record. A later write to the parent then needs no copy.
- The check happens at write time, so the cost is paid only by code that writes. A pipeline that derives many objects and only reads them never copies the data.
Which operations share data
Operations that only rearrange labels or pick existing data can share it. Operations that compute new values must allocate new arrays anyway.
| Operation | Shares data with the parent? | Why |
|---|---|---|
| `df["a"]` | Yes | Returns the existing column |
| `df[["a", "b"]]` | Yes | Selects existing columns |
| `df.reset_index(drop=True)` | Yes | Only the index changes |
| `df.rename(columns={...})` | Yes | Only labels change |
| `df.head(2)` | Yes | A slice of existing data |
| `df.copy()` | No | An explicit, immediate copy |
| `df + 1` | No | Computes new values |
| `df[df["a"] > 1]` | No | Selects rows into new arrays |
| `df.sort_values("a")` | No | Reorders rows into new arrays |
Treat this table as typical behavior, not as a contract. Pandas can change which methods share data between releases, because sharing is invisible when the rule holds. Do not write code that branches on it.
Writing to the parent also triggers a copy
The rule works in both directions. If you modify the parent after deriving an object from it, pandas must still protect the derived object.
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
df2 = df.reset_index(drop=True)
df.loc[0, "a"] = 100 # the parent is written first this time
print(df["a"].tolist()) # [100, 2, 3]
print(df2["a"].tolist()) # [1, 2, 3], df2 is unaffected
print(np.shares_memory(df["a"].to_numpy(), df2["a"].to_numpy())) # FalsePandas does not care which object is the "original." It only sees an array used by two objects and a write about to hit one of them. The writer gets the copy.
Several objects can share one array
Sharing is not limited to pairs. Any number of objects can point at the same array, and a write copies only for the object being written.
import numpy as np
import pandas as pd
def shares(x, y):
"""Return True if the first columns of x and y use the same memory."""
return np.shares_memory(x.iloc[:, 0].to_numpy(), y.iloc[:, 0].to_numpy())
df = pd.DataFrame({"a": [1, 2, 3]})
df2 = df.reset_index(drop=True)
df3 = df.rename(columns={"a": "x"})
print(shares(df, df2), shares(df, df3), shares(df2, df3)) # True True True
df2.loc[0, "a"] = 100
print(shares(df, df2)) # False, df2 now owns its data
print(shares(df, df3)) # True, df and df3 still share
print(shares(df2, df3)) # FalseOnly df2 paid for a copy. df and df3 still share the original array, and they will separate when one of them is written to.
A copy also happens only once per owner. After df2 has its own array, nothing else uses it, so later writes to df2 are plain in-place writes with no further copying.
Working through a chain of operations
Here is a realistic function. It derives several objects and writes to only one of them.
import pandas as pd
def add_flag(frame: pd.DataFrame) -> pd.DataFrame:
out = frame.reset_index(drop=True) # lazy, shares data with frame
out["flag"] = out["score"] > 50 # new column, computed
out.loc[0, "score"] = 0 # first write to the shared "score" data
return out
raw = pd.DataFrame({"score": [70, 40, 90]}, index=["x", "y", "z"])
result = add_flag(raw)
print(raw["score"].tolist()) # [70, 40, 90]
print(result["score"].tolist()) # [0, 40, 90]The function modifies out, and raw is unchanged. In pandas 2.x with the old behavior, you could not tell from this code whether raw was modified. Many people added frame = frame.copy() at the top "just in case." Under Copy-on-Write that line costs memory and time and protects against nothing. A later chapter covers when a defensive .copy() is still needed.
The new flag column does not copy anything shared. The comparison creates fresh values, and adding a column only changes out. The loc write is where the one copy of score happens, and it happens only for out.
What the copy covers
When the copy happens, pandas copies the shared data held by the written object. That can be more than the cells you changed.
- Writing one cell of a large column copies the whole column's data, or the block it lives in, not one value.
- If you derive many objects and then write to each of them once, you pay for one copy per object.
- A write loop over a shared object copies only on the first iteration. The later iterations write into the private copy.
A loop such as this one is a common source of unexpected slowness:
import pandas as pd
df = pd.DataFrame({"a": range(5)})
for i in range(len(df)):
view = df.iloc[[i]] # derived object
df.loc[i, "a"] = i * 10 # may copy, because view still references the data
print(view["a"].iloc[0], df["a"].iloc[i])Each pass keeps a derived object alive, and view is not released until it is reassigned on the next pass. The write to df therefore sees a live reference and may have to copy. Whether this exact snippet copies depends on how df.iloc[[i]] is evaluated. The view line shows the rule at work: view keeps its original value, and df gets the new one. The lesson is general: keeping derived objects alive while you write to the parent can trigger copies, so avoid holding on to temporaries you no longer need.
Read-only arrays keep the sharing safe
Lazy sharing only works if nobody can modify shared memory behind pandas's back. NumPy arrays obtained from pandas objects could do exactly that, so pandas marks them read-only.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy()
print(arr.flags.writeable) # False
arr = df["a"].to_numpy().copy()
arr[0] = 100 # allowed, df is not affected
print(df["a"].iloc[0]) # 1An attempt to assign into the read-only array raises a ValueError instead of silently changing df and every object that shares its data. A later chapter covers how to handle this in code that expects writable arrays. For now, note that this restriction is part of what makes lazy copies safe.
Edge cases and common mistakes
Assuming sharing is permanent or guaranteed. np.shares_memory returning True today tells you nothing you can build on. The guarantee is the rule, not the memory layout.
Writing in a loop while holding references. As in the loop above, a live derived object can force a copy on each write to the parent. Release or avoid temporaries when you write repeatedly.
Expecting df2 = df to be a derived object. Assigning a name creates a second reference to the same Python object, not a new DataFrame. Both names refer to one object, so a modification through one name is visible through the other. Copy-on-Write governs objects derived by pandas methods, not extra names for one object.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
alias = df # same object, not derived
alias.loc[0, "a"] = 100
print(df["a"].iloc[0]) # 100, alias and df are the same objectUsing .copy() to "be safe" everywhere. An explicit .copy() always allocates and copies immediately. It defeats the laziness and, with large frames, doubles memory use for no benefit when the rule already protects you.
Reading memory use from sharing. A lazily derived object reports the same memory_usage() as its parent, but the two do not use double the memory. Summing per-object numbers overcounts when data is shared.
Summary of the model
- A lazily derived object points at the parent's data and costs almost nothing.
- Pandas records which objects share each array.
- A write to any sharing object first copies the data for that object, then writes.
- After that, the writer owns its data and writes in place.
- Reads never copy.
The guarantee stays the same throughout: changes to one object never appear in another.
Exercise
You run df2 = df.reset_index(drop=True) and then df.loc[0, "a"] = 100. Which object gets a copy of the data, and does df2 see the change?
Show answer
The write is to df, so df gets its own copy of the shared array before the write. df2 keeps the original array and does not see the change. Pandas copies for whichever object is written to, not for the one that was derived.
Exercise
Given df = pd.DataFrame({"a": [1, 2, 3]}), write code that creates two derived objects with rename and reset_index(drop=True), writes to only one of them, and prints whether df still shares memory with the other one. What do you expect it to print?
Show answer
One solution:
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
r1 = df.resetindex(drop=True)
r2 = df.rename(columns={"a": "x"})
r1.loc[0, "a"] = 100
print(np.sharesmemory(df.iloc[:, 0].tonumpy(), r2.iloc[:, 0].tonumpy()))
It prints True. Only r1 was written to, so only r1 received a copy. df and r2 still share the original array.
Exercise
A colleague adds frame = frame.copy() at the start of every function that modifies a DataFrame argument, "to avoid changing the caller's data." Under pandas 3, is the copy needed for that purpose, and what does it cost?
Show answer
It is not needed for that purpose. Under Copy-on-Write, the function receives the caller's object, but a derived object such as frame.reset_index(drop=True) or frame[["a", "b"]] is protected, and writes to it never change the caller's data. The exception is a function that modifies its argument directly, such as frame.loc[0, "a"] = 1 on the object passed in. That changes the caller's object because it is the same object, not a derived one. For derived objects, the explicit copy costs an immediate allocation and a full copy of the data, which the lazy mechanism would have deferred or avoided if the function never wrote.