Sub topic 5
Lazy copies: how pandas shares data until you write
This chapter assumes you know the Copy-on-Write rule from earlier in this tutorial: a DataFrame or Series derived from another object never changes the original. You should also be comfortable with .loc and .iloc. A basic idea of NumPy arrays helps, but you don't need it.
The rule sounds expensive. If every derived object acts as an independent copy, then df.reset_index(drop=True) on a large table should duplicate all of its data. It doesn't. pandas keeps the copy lazy and defers it until it's needed.
Independent in behavior, shared in memory
Two things are true at once:
- Behavior: the derived object is independent. Writing to it never affects the parent, and writing to the parent never affects it.
- Memory: right after the operation, both objects may point at the same underlying data.
The sharing is an optimization. You can't observe it through normal pandas code, because the first write to either object triggers a real copy.
Watching the copy happen
You can check the sharing with np.shares_memory.
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]The sequence is:
reset_index(drop=True)builds a new DataFrame object but reuses the column data.- The first
printshowsTrue, so no data was duplicated. df2.loc[0, "a"] = 100is a write. Before changing anything, pandas copies the data thatdf2needs.- The second
printshowsFalse.df2now has its own memory, anddfstill holds the original values.
Only the object being written gets a new copy. The other object keeps the original data.
It works in both directions
Writing to the parent is also a write that triggers a copy. The child is unaffected.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
df2 = df.reset_index(drop=True)
df.loc[0, "a"] = 100 # df gets its own data, df2 keeps the old data
print(df["a"].tolist()) # [100, 2, 3]
print(df2["a"].tolist()) # [1, 2, 3]pandas tracks references to the underlying data. When you write, pandas checks whether anything else still references that data. If something does, it copies first. If nothing does, it writes in place with no copy.
That last point matters. A DataFrame with no other references is modified directly, so repeated writes to one object don't copy each time.
What triggers a lazy copy
Many methods return a new object without copying data. Typical examples are:
reset_index,rename,set_axisand similar methods that change labels- selecting a column with
df["a"] df.head(),df.iloc[:2]and other slicesdf.copy(deep=False)style shortcuts that you rarely need now
The details of which methods defer the copy can change between releases, so don't write code that depends on sharing. Rely on the rule: the result behaves as an independent object.
What counts as a write
A write is any operation that changes values in place on an existing object:
df.loc[...] = valueanddf.iloc[...] = valuedf["new_col"] = ..., which replaces or adds a column on that DataFrame- in-place methods such as
fillna(..., inplace=True)on a derived object
Operations that return a new object, such as df.assign(...) or df.dropna(), are not writes to df. They create a derived object and leave df alone.
Practical consequences
You don't need to manage sharing yourself. Three habits follow from how it works:
- Trust the rule. If a function receives a DataFrame and modifies it, the caller's object is only affected when you pass the same object, not a derived one.
- Expect the first write to cost something. A chain of cheap derivations can be followed by one slower write that performs the copy. If a write is unexpectedly slow, this is a likely reason.
- Don't test for sharing in production code.
np.shares_memoryis a good tool for learning and for debugging memory use. It isn't a stable interface for application logic.
The next chapters build on this. Because the shared data must never be changed through one object, arrays that expose it are read-only, and many defensive .copy() calls become unnecessary.
Exercise
You run df2 = df.rename(columns={"a": "x"}), then df.loc[0, "a"] = 100. What happens to df2, and when does pandas copy data?
Show answer
df2 is unchanged. rename returns a new object that initially shares data with df. The write to df is the first modification, so pandas copies the data that df needs before changing it. df2 keeps the original values.
Exercise
A function receives df, runs out = df.reset_index(drop=True), then sets out.loc[0, "a"] = 5 and returns out. Does the caller's df change? Does the function copy the whole DataFrame when it calls reset_index?
Show answer
The caller's df does not change. reset_index shares data lazily, so it doesn't copy at that point. The .loc write is what triggers the copy, and only out receives the new data.