Sub topic 9
Performance and memory effects
This chapter assumes you know the Copy-on-Write rule from earlier in this tutorial: a derived DataFrame or Series never changes the object it came from. It also assumes you know that pandas delays the real copy until a write. Here we look at what that means for speed and memory, and how to measure it.
Why laziness saves work
Before pandas 3, many operations either copied data to be safe or returned a view you had to be careful with. That led to habitual .copy() calls and to extra memory use. Under Copy-on-Write, a derived object starts out sharing data with its parent. Creating it costs almost nothing, because no data moves. Only a write forces a copy.
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": np.arange(1_000_000), "b": np.arange(1_000_000)})
derived = df.reset_index(drop=True)
chained = df.rename(columns={"a": "x"}).reset_index(drop=True)
explicit = df.copy()
print(np.shares_memory(df["a"].to_numpy(), derived["a"].to_numpy())) # True
print(np.shares_memory(df["a"].to_numpy(), chained["x"].to_numpy())) # True
print(np.shares_memory(df["a"].to_numpy(), explicit["a"].to_numpy())) # FalseThe first two results are True. The rename and reset_index calls built new objects, but neither one duplicated the column data. A long method chain therefore adds no memory for its intermediate results. df.copy() is the only line that allocates a full second set of data.
What a write costs
The copy happens when you first modify an object that still shares data. After that, the object owns its data and later writes are ordinary in-place writes.
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": np.arange(1_000_000)})
derived = df.reset_index(drop=True)
derived.loc[0, "a"] = -1 # first write: pandas copies here
print(np.shares_memory(df["a"].to_numpy(), derived["a"].to_numpy())) # False
derived.loc[1, "a"] = -2 # second write: no new copy needed
print(df["a"].iloc[:2].tolist()) # [0, 1]pandas copies the data it needs to modify. When several columns are stored together in one block, that can be more than the single column you touched. The copy also depends on references. If the other object has already been garbage collected, nothing else shares the data, and pandas can skip the copy.
Measuring the difference
Timing shows the gap between a lazy derive and an explicit copy. The numbers depend on your machine, so run this yourself.
import time
import numpy as np
import pandas as pd
df = pd.DataFrame(
np.random.default_rng(0).random((2_000_000, 5)),
columns=list("abcde"),
)
def timed(func):
start = time.perf_counter()
func()
return time.perf_counter() - start
print(f"df.copy(): {timed(df.copy):.4f}s")
print(f"reset_index(...): {timed(lambda: df.reset_index(drop=True)):.4f}s")df.copy() has to move about 80 MB. The reset_index call mostly builds a new index and a new wrapper object, so it is much faster. The gap grows with the size of the data.
Practical consequences
- Remove defensive copies. A line like
subset = df[df["x"] > 0].copy()made sense when a view might leak writes back todf. Under Copy-on-Write that guarantee is built in, so the.copy()only costs time and memory. Keep it only when you want an independent object immediately, for example to separate memory ownership before handing the data to a long-lived structure. - Method chains are cheap. Use as many steps as clarity calls for. Each step shares data until something writes.
- A single write can still be expensive. If you derive a large object and then modify one value, the first write copies the data. The cost moves from the derive step to the write, and it is paid at most once per object.
- Memory peaks happen at the write. If a pipeline derives many large objects and then modifies each one, they will all copy eventually. Lazy copying delays the allocation but does not remove it.
- Writes through references can multiply copies. Holding on to an intermediate variable keeps the data shared, so a later write copies it. Dropping the variable with
del, or letting it go out of scope, can avoid that copy.
Summary table
| Operation | Copies data immediately? | Notes |
|---|---|---|
| `df.reset_index(drop=True)` | No | Shares data until a write |
| `df.rename(columns=...)` | No | Shares data until a write |
| `df.copy()` | Yes | Use only when you need immediate independence |
| First write to a derived object | Yes, for the written data | Later writes are in place |
| Write to the last remaining reference | No | Nothing else shares the data |
Exercise
A colleague writes clean = raw.dropna().reset_index(drop=True).copy() on a 4 GB DataFrame, then only reads from clean. Which part is unnecessary under pandas 3, and why?
Show answer
The final .copy(). Under Copy-on-Write, clean can never modify raw, so the defensive copy gives no safety. Since clean is only read, it also would never have triggered a copy on its own. The .copy() allocates a second full set of data for nothing. (dropna() may still copy the rows it keeps, but that is part of the operation itself.)
Exercise
You run b = a.reset_index(drop=True) and then b.loc[0, "x"] = 5 on a large DataFrame. At which line does pandas copy the data, and what happens on a second write to b?
Show answer
It copies at the b.loc[0, "x"] = 5 line, which is the first write to b. The second write is a normal in-place write, because b now owns its data.