Sub topic 9
Performance and memory effects
Earlier chapters showed that every derived object in pandas 3 behaves like an independent copy. This chapter covers what that costs and saves. You will see where memory is shared, when the real copy happens, which operations still allocate, and how to check these claims in your own code.
This chapter assumes you know the Copy-on-Write rule (a derived object never changes the object it came from) and the idea of lazy copies. It also assumes you are comfortable reading short NumPy-based snippets. Exact timings and byte counts depend on your machine, so the code below prints comparisons instead of fixed numbers.
The trade that Copy-on-Write makes
Before pandas 3, pandas often copied data eagerly to be safe. Many methods returned a full copy "just in case" you modified the result. Other operations returned views that shared memory with the parent, and writing to such a view could change the parent.
Copy-on-Write (CoW) replaces both behaviors with one strategy:
- A method that does not need new data returns an object that shares the parent's memory.
- Pandas records that the memory is shared.
- When either object is written to, pandas copies the data for the object being written. The other object keeps the original.
The result is that most reads and reshaping steps cost close to nothing, and you pay for a copy only when a write happens on shared data.
Which operations are lazy and which allocate
An operation is lazy when its result can point at the parent's existing arrays. It allocates when it has to build new values.
| Operation | Allocates new data now? | Why |
|---|---|---|
| `df.reset_index(drop=True)` | No | Only the index changes. The column data is reused. |
| `df.rename(columns=...)` | No | Only labels change. |
| `df["a"]` | No | The Series points at the column's data. |
| `df.iloc[:100]` (a slice of rows) | No | A slice is a window onto the same memory. |
| `df[df["a"] > 0]` (boolean mask) | Yes | Selected rows must be gathered into new arrays. |
| `df.sort_values("a")` | Yes | Rows are reordered, which produces new arrays. |
| `df.copy()` | Yes | A full copy is what you asked for. |
| First write to a shared object | Yes | This is the deferred copy. |
A useful rule of thumb: if the result has the same values in the same layout as the parent, expect sharing. If the values are rearranged, filtered, or computed, expect an allocation.
Measuring sharing and allocation
You do not have to trust the table. np.shares_memory tells you whether two objects point at the same data, and tracemalloc reports memory allocated by Python and NumPy.
The first script compares the peak memory of a chain of lazy operations with the peak memory of a deep copy:
import tracemalloc
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame(rng.random((1_000_000, 4)), columns=list("abcd"))
data_mb = df.memory_usage(index=False).sum() / 1e6
def peak_mb(func):
tracemalloc.start()
result = func() # keep the result alive until we read the peak
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak / 1e6, result
lazy_mb, lazy = peak_mb(lambda: df.reset_index(drop=True).rename(columns=str.upper))
copy_mb, deep = peak_mb(lambda: df.copy())
print(f"data size: {data_mb:.1f} MB")
print(f"lazy chain peak: {lazy_mb:.2f} MB")
print(f"deep copy peak: {copy_mb:.2f} MB")
print(np.shares_memory(df["a"].to_numpy(), lazy["A"].to_numpy())) # True
print(np.shares_memory(df["a"].to_numpy(), deep["a"].to_numpy())) # FalseThe data is about 32 MB. The lazy chain peaks well under 1 MB, because it only builds a new index and new labels. The deep copy peaks at roughly the size of the data. The two shares_memory lines confirm the reason.
When the deferred copy happens
A shared object stays shared until one side is written to. At that point the writer gets its own copy. If nothing else references the data, no copy is needed and the write happens in place.
Pandas tracks this with references from each object to the memory it uses. When the other object is deleted or garbage collected, the reference disappears, and the next write is cheap. The following script checks that behavior by looking at where the column data lives before and after a write:
import numpy as np
import pandas as pd
def address(df):
return df["a"].to_numpy().__array_interface__["data"][0]
def write_moves_data(keep_other):
df = pd.DataFrame({"a": np.arange(5)})
other = df.reset_index(drop=True) # shares memory with df
if not keep_other:
del other # drop the only other reference
before = address(df)
df.loc[0, "a"] = 100
return address(df) != before
print(write_moves_data(keep_other=True)) # True: shared, so the write copied
print(write_moves_data(keep_other=False)) # False: not shared, written in placeWhen other is alive, the write must copy so that other still sees the old values. When other is gone, pandas writes directly into the existing memory.
Three practical consequences follow:
- Only the first write pays. After pandas copies the data for
df,dfowns a private block. Further writes todfdo not copy again. - Temporary objects cost nothing. Intermediate results that you no longer reference do not force copies on later writes.
- Long-lived references can add a copy. If you keep an old derived object around, such as a saved snapshot, the first write to the original has to copy. This is the correct behavior, because the snapshot must not change. It also means you should delete references you do not need.
How much is copied
A DataFrame stores columns of the same dtype together in internal blocks, so the copy on first write can be larger than the one column you touched. If df has 50 float columns in one block and you write to one cell, pandas may copy the whole block. Treat the worst-case cost as the size of the block holding the target column, not the size of one column.
Replacing a whole column is different. This statement does not copy the other columns:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]})
df["a"] = df["a"] * 2
print(df)The multiplication allocates the new values for a, and the assignment swaps them in. Column b is untouched.
Operations that stay lazy through a pipeline
Because many steps share memory, long method chains cost much less than before. Each stage that only relabels or selects adds almost no memory, and a later stage that builds new values allocates only those values.
import numpy as np
import pandas as pd
df = pd.DataFrame(
{
"price": np.linspace(10, 20, 1_000),
"qty": np.arange(1_000),
}
)
result = (
df.rename(columns={"qty": "quantity"}) # lazy
.reset_index(drop=True) # lazy
.assign(total=lambda d: d["price"] * d["quantity"]) # allocates only "total"
)
print(np.shares_memory(df["price"].to_numpy(), result["price"].to_numpy())) # True
print(result.columns.tolist()) # ['price', 'quantity', 'total']In result, the price and quantity columns still share memory with df, and only total is new. If you later write to result["price"], the copy happens for result at that moment. df is unaffected, which is the same guarantee you had before, with less work up front.
Removing defensive copies
In pandas 2.x code, you often see .copy() calls added to prevent accidental changes to the caller's data:
def clean(df):
df = df.copy() # defensive copy
df["name"] = df["name"].str.strip()
return dfUnder CoW, the caller's DataFrame cannot change through df, so the copy is not needed. Without it, the function does less work:
import pandas as pd
def clean(df):
df = df.copy(deep=False) # optional, see the note below
df["name"] = df["name"].str.strip()
return df
original = pd.DataFrame({"name": [" ann ", "bob "], "n": [1, 2]})
cleaned = clean(original)
print(original["name"].tolist()) # [' ann ', 'bob ']
print(cleaned["name"].tolist()) # ['ann', 'bob']The simplest version drops the copy line entirely. Assigning a new column to df inside the function never touches the caller's object, and column n stays shared. Removing a defensive copy on a large frame saves both time and a full duplicate of the data.
When a copy is still the right tool
CoW does not make .copy() obsolete. These cases still call for it:
- Releasing a large parent. A small derived object can keep the parent's whole array alive. If you take a slice of 10 rows from a 10 GB column and store only the slice, the 10 GB stays in memory. Call
.copy()on the slice so the parent can be freed. - Writing to a NumPy array. Arrays that expose pandas data are read-only under CoW. Use
.to_numpy().copy()when you need a writable array, as the previous chapter showed. That copy is explicit, and it is the one place where you pay for the allocation yourself. - Isolating data for another library. If code outside pandas keeps a reference to the underlying array and you want to guarantee no later interaction, copy at the boundary.
- Breaking a long-lived snapshot. If you need a frozen reference for later comparison and also plan to write to the original, a snapshot made with
.copy()makes the cost happen once, at a time you choose, instead of at the first write.
The slice case is easy to check:
import numpy as np
import pandas as pd
big = pd.DataFrame({"a": np.arange(1_000_000)})
head_lazy = big["a"].iloc[:10]
head_owned = big["a"].iloc[:10].copy()
print(np.shares_memory(big["a"].to_numpy(), head_lazy.to_numpy())) # True
print(np.shares_memory(big["a"].to_numpy(), head_owned.to_numpy())) # Falsehead_lazy keeps the million-row array alive for as long as it exists. head_owned holds only its own 10 values.
Common mistakes
- Copying "to be safe" out of habit. Extra
.copy()calls on large frames double memory use briefly and cost time for no benefit. Search for them during migration. - Expecting a write to a shared object to be free. The first write after sharing allocates. In a tight loop that creates a new derived object on every iteration and then writes to it, every iteration pays for a copy.
- Writing cell by cell in a Python loop.
df.loc[i, "a"] = valuefor each row is slow whatever CoW does, because each call has overhead. Compute the whole column with vectorized operations and assign it once. - Assuming a boolean filter is lazy.
df[mask]builds new arrays. Memory use grows with the number of selected rows. - Holding on to old references. An unused variable such as
df_beforeforces a copy on the next write todf, and it keeps the old data in memory. Delete it, or let it go out of scope. - Measuring with
memory_usage()alone.memory_usage()reports the size of each object as if it were independent. It does not show that two frames share the same arrays. Usenp.shares_memoryortracemallocto see real allocations.
Putting it together
For a typical data-cleaning script, CoW changes the cost profile in these ways:
- Reading, relabeling, and slicing steps are cheap, so you can write long chains without worrying about hidden copies.
- Steps that compute or rearrange values allocate what they need and nothing more.
- Writes copy at most once per object, and not at all when nothing else shares the data.
- Memory stays in use as long as any object points at it, so release large parents by copying small results and deleting names you no longer need.
Exercise
You have a DataFrame df and write snap = df.reset_index(drop=True). You then run df.loc[0, "a"] = 5 and later df.loc[1, "a"] = 6. How many times does pandas copy the data for df, and why? What changes if you run del snap right after creating it?
Show answer
With snap alive, the first write copies the data for df (one copy), because snap still shares the original block and must keep its old values. After that copy, df owns a private block, so the second write happens in place with no copy. If you run del snap right after creating it, nothing else references the data, so neither write copies and both happen in place.
Exercise
A function receives a 5 GB DataFrame, adds one new column with df["z"] = df["x"] + df["y"], and returns it. The first line of the function is df = df.copy() to protect the caller's data. Should you keep that line under pandas 3? What is allocated if you remove it?
Show answer
Remove it. Under Copy-on-Write, assigning a new column to df inside the function cannot change the caller's object, so the defensive copy only duplicates 5 GB. Without it, only the new column z is allocated, and the existing columns stay shared with the caller's DataFrame.
Exercise
You keep only small = huge["a"].iloc[:100] from a very large DataFrame huge, then delete huge. Memory use stays high. Why, and how do you fix it?
Show answer
small is a lazy slice, so it still points at the full column array and keeps it alive even after huge is deleted. Create it with huge["a"].iloc[:100].copy() so it owns only its 100 values, and the large array can then be freed.