skip to content

In pandas 3.0, when does Copy-on-Write actually copy data, and why does `df = df.reset_index(drop=True)` avoid that copy?

level: middleimportance: should knowfreq 40%

answer

  1. behaves as a copy, shares underneath
  2. copy deferred to the first write
  3. count the live references
  4. rebinding drops the old one

basics

~20 s

pandas 3.0 shares data between a result and its source and copies only when one of them is written while both still reference it. Rebinding to the same name drops the old frame, so no copy is needed.

solid answer

~40 s

In pandas 3.0 every indexing result and method output behaves as a copy, but methods like `rename`, `drop(columns=...)` or `reset_index` hand back an object that shares its parent's data. pandas tracks that sharing and makes the real copy only when one of the objects is written while the other still references the data. If I write `df2 = df.reset_index(drop=True)` and then set a value in `df2`, pandas must copy first so `df` keeps its values. If I write `df = df.reset_index(drop=True)`, the old frame loses its last reference, so the new one is the sole owner and the write happens in place. `.copy()` still makes an eager copy, while the `copy=` keyword on those methods is deprecated and does nothing.

code

python · 13 lines
python
import pandas as pd

customers = pd.DataFrame({"customer_id": [101, 102], "balance": [120.0, -40.0]})

# Two live references: the write must copy first
reindexed = customers.reset_index(drop=True)   # shares customers' data
reindexed.iloc[0, 1] = 0.0                     # pandas copies, then writes
print(customers.iloc[0, 1], reindexed.iloc[0, 1])   # 120.0 0.0

# One live reference: the write happens in place
customers = customers.reset_index(drop=True)   # old frame is released
customers.iloc[0, 1] = 0.0                     # no copy needed
print(customers.iloc[0, 1])                    # 0.0

go deeper

for a junior

Recall that a 3.0 result behaves as a copy, but that pandas avoids copying until something is written to data another object still uses.

for a middle

Walk through df2 = df.reset_index() versus df = df.reset_index() and explain the reference that forces, or avoids, the copy on the first write.

for a senior

Use the reference rule to explain memory spikes on a first write in a long pipeline and to decide where an explicit .copy() releases a large parent.

for a principal

Weigh rebinding names and explicit copies as team conventions: fewer live references save copies, but code readability and debugging access to earlier frames also matter.

## Two layers: the rule and the mechanism pandas 3.0 Copy-on-Write has a user-facing **rule** and an internal **mechanism**, and it pays to keep them apart. - **The rule:** every new Series or DataFrame returned by indexing or by a method *behaves as if* it were a copy. Changing it never changes the object it came from, and the other way round. - **The mechanism:** pandas does not actually copy at that point. Where an operation does not need new data, the result **shares** its parent's data, and pandas tracks which objects reference the same data. The real copy is **deferred until a write** happens to data that some other live object still references. That deferral is the "copy-on-write" the mode is named after. The release notes put it plainly: pandas uses views as much as possible under the hood and only copies when needed to guarantee the "behaves as a copy" behaviour. ## When the copy happens Take a customer frame and a method that does not need to change any values: ```python customers = pd.DataFrame({"customer_id": [101, 102], "balance": [120.0, -40.0]}) renamed = customers.rename(columns={"balance": "balance_usd"}) ``` At this point `renamed` and `customers` share the same balance values; nothing was copied. What happens next depends on the write: 1. **Nobody writes.** No copy is ever made. The rename cost almost nothing. 2. **`renamed.iloc[0, 1] = 0.0`.** The data is still referenced by `customers`, so pandas copies it first and then writes into the copy. `customers` keeps 120.0. 3. **`customers.iloc[0, 1] = 0.0`.** Same in reverse: `customers` gets its own data before the write, and `renamed` keeps the old value. The pandas user guide names `DataFrame.drop` with `axis=1` and `DataFrame.rename` as popular examples of methods that return such lazy results; `reset_index` is its worked example. Some operations cannot share at all: filtering rows with a boolean mask, for instance, has to build new arrays anyway, so its result owns its data from the start. ## Why rebinding the name avoids the copy The copy in case 2 exists only because two live objects reference the same data. Remove one of them and the copy is unnecessary: ```python customers = customers.reset_index(drop=True) customers.iloc[0, 1] = 0.0 # written in place, no copy ``` When the result of `reset_index` is assigned back to the same name, the old frame loses its last reference and is released. The new `customers` is then the only object holding that data, so the write goes straight in. The user guide lists the opposite as a **pattern to avoid**: keeping `df` and `df2` both alive when you no longer need `df` keeps an extra reference around, which forces a copy on the first write and hurts performance. | Pattern | Live references to the data at the write | Copy on write? | |---|---|---| | `df2 = df.reset_index(drop=True); df2.iloc[0, 0] = v` | two (`df`, `df2`) | yes | | `df = df.reset_index(drop=True); df.iloc[0, 0] = v` | one | no | | `df.iloc[0, 0] = v` on a freshly built frame | one | no | ## What `.copy()` and the `copy` keyword mean now - **`df.copy()`** still makes an **eager**, independent copy; its `deep` argument defaults to `True`. Use it when you want the copy now, for example so a small subset stops referencing a large parent. - **`df.copy(deep=False)`** returns a shallow copy that, under Copy-on-Write, is itself a lazy copy: changes to either object are no longer reflected in the other, which is the opposite of the 2.x behaviour its docstring warns about. - **The `copy=` keyword** of methods such as `rename`, `astype`, `reindex`, `set_axis`, `align` and `merge` is **deprecated in pandas 3.0**. It has no effect, passing it emits a `Pandas4Warning`, and the release notes say it can be safely removed. ## What to say in an interview A practical consequence for long pipelines: the cost of a copy moves from the line that created the result to the first line that writes to it. A profile that shows a sudden memory jump on a harmless-looking `iloc` assignment is often this deferred copy, paid because an earlier frame is still alive. The short version: results behave as copies; pandas shares data until a write to shared data forces a real copy; a write to data nobody else references happens in place; so reassign to the same name when you no longer need the original, reach for `.copy()` only when you want an eager copy, and drop `copy=` arguments from 3.0 code.

  • When is an explicit `.copy()` still worth calling in pandas 3.0?
    When you want an eager, independent copy now rather than a deferred one. The usual case is keeping a small subset of a large frame: an explicit copy lets the subset stop referencing the parent's data, so the parent can be released, and it also means a later write will not pay for a copy at an awkward moment.
  • What does `df.copy(deep=False)` give you under Copy-on-Write?
    A new object that initially shares `df`'s data and index without copying them, but which, under Copy-on-Write, no longer sees changes made to `df`, nor passes its own changes back. The first write to either object makes pandas copy. In 2.x without CoW a shallow copy did reflect changes in both directions, so code relying on that link breaks.

It is like two people reading one shared document: nobody photocopies it while they only read, but the moment one wants to scribble on it, they get their own copy first. If the other reader has already left, the scribbler just writes on the original.

  • Every pandas 3.0 method result is copied eagerly when it is returned
  • Passing copy=False to rename or astype makes the result a writable view
  • A shallow copy with deep=False still reflects changes to the original
  • Keeping the original frame alive beside its result costs nothing extra
  • Copy-on-Write copies on every write, even when nothing shares the data

Assumes pandas 3.0, where Copy-on-Write is always on and the copy keyword is deprecated; in 2.x most methods copied eagerly unless CoW was enabled.