Sub topic 7
Dropping unneeded defensive copies
This chapter assumes you know the basic Copy-on-Write rule from earlier in the tutorial: a DataFrame or Series derived from another object never changes the object it came from. It also assumes you are comfortable with .loc assignment and with the difference between two names for one object and two separate objects. A basic idea of NumPy arrays helps for the later sections.
Why defensive copies exist
In pandas 2.x and earlier, selecting rows or columns could return a view or a copy, and you often could not tell which. A view shares memory with its parent, so a write could change the parent. A copy does not.
Writing to the result of a selection could also trigger SettingWithCopyWarning. Many codebases grew a habit to cope:
- Add
.copy()after every filter, "just to be safe". - Add
.copy()at the top of every function, so it cannot change its argument. - Add
.copy()before storing a DataFrame on an object.
Each of these was a defensive copy. It bought predictable behavior at the price of extra memory and time. In pandas 3, derived objects always behave as copies, so many of these calls do nothing useful.
This chapter shows which defensive copies you can delete, which ones you must keep, and how to tell them apart.
The test: derived object or same object?
Copy-on-Write protects you when one object is derived from another by an operation. Filtering, selecting columns, reset_index, rename, sort_values, head and assign all produce derived objects. A write to the result never reaches the source.
Copy-on-Write does not protect you when two names refer to the same object. Plain assignment (b = a) and passing an argument into a function both create a second name, not a second object. A write through either name is visible through the other.
Ask one question before keeping a .copy(): is the object I am about to modify derived from something I want to protect, or is it that same object?
Copies you can remove
After filtering or selecting
The classic case is a filter followed by a modification. Under pandas 2.x you wrote .copy() to avoid a warning and to be sure the original stayed intact. Under pandas 3 the result is already independent.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
subset = df[df["a"] > 1] # no .copy() needed
subset.loc[subset.index[0], "b"] = 100
subset["c"] = subset["a"] * 2
print(subset)
print(df) # unchanged: still two columns, original valuessubset can be modified freely. df keeps its original values and its original columns.
Chained `.copy()` calls in a pipeline
Defensive copies tend to pile up in cleaning functions. Here is a typical "before":
import pandas as pd
def prepare_before(df):
out = df.copy()
out = out[out["amount"] > 0].copy()
out = out.reset_index(drop=True).copy()
out["amount_eur"] = out["amount"] * 0.9
return outEvery .copy() here makes a full copy of the data, and each intermediate result is discarded right away. Here is the same function without them:
import pandas as pd
def prepare_after(df):
out = df[df["amount"] > 0].reset_index(drop=True)
out["amount_eur"] = out["amount"] * 0.9
return out
raw = pd.DataFrame({"amount": [10.0, -5.0, 20.0]})
snapshot = raw.copy()
result = prepare_after(raw)
pd.testing.assert_frame_equal(raw, snapshot) # input untouched
pd.testing.assert_frame_equal(result, prepare_before(raw))
print(result)out is derived from df by filtering, so assigning a new column to out cannot affect raw. The assertions confirm that the input is unchanged and that both versions give the same result. The snapshot line is a deliberate copy in a test, to compare against later.
Copies meant to silence `SettingWithCopyWarning`
If a .copy() exists only because a warning appeared after a filter, remove it. SettingWithCopyWarning is no longer emitted in pandas 3, because the situation it described, a write that might or might not reach the parent, cannot occur.
A warning that does still appear is ChainedAssignmentError. It means you wrote something like df["a"][0] = 100, which updates a temporary object. Adding .copy() will not fix that. Rewrite it as a single .loc assignment, as covered in the chained assignment chapter.
Copies "to keep the original safe"
Many people copy a frame before calling a function that returns a modified version. If the function builds its result through derived objects, the original is already safe. The function does not need .copy() on the way in, and the caller does not need to pass df.copy().
Copies you must keep
Two names for one object
Copy-on-Write only separates objects that are derived from each other. A function parameter is the same object as the caller's variable. If the function assigns a column on it, the caller sees the change:
import pandas as pd
def add_total_in_place(df):
df["total"] = df["a"] + df["b"] # modifies the caller's object
return df
def add_total(df):
return df.assign(total=df["a"] + df["b"]) # builds a new object
orig = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
add_total(orig)
print(list(orig.columns)) # ['a', 'b']
add_total_in_place(orig)
print(list(orig.columns)) # ['a', 'b', 'total']The first function does not need a defensive copy, because assign returns a new object. The second one mutates its argument. You have two fixes: switch to a method that returns a derived object, or keep a .copy() at the top. Prefer the first, since it makes no copy until a write needs one, and the second is a full copy up front.
The same applies when you store a DataFrame on an object:
import pandas as pd
class Report:
def __init__(self, data):
self.data = data # same object as the caller's
class SafeReport:
def __init__(self, data):
self.data = data.copy() # independent object
df = pd.DataFrame({"a": [1, 2, 3]})
shared = Report(df)
safe = SafeReport(df)
df.loc[0, "a"] = 99
print(shared.data.loc[0, "a"]) # 99, same object
print(safe.data.loc[0, "a"]) # 1, independentIf the class should be isolated from later in-place changes by the caller, keep the .copy(). If you use data.reset_index(drop=True) or any other method that returns a new object, you get the same isolation and pandas defers the copy.
Python objects inside an object column
DataFrame.copy() copies the pandas data. It does not recursively copy Python objects stored inside cells. A list in a cell is still the same list in both frames:
import copy
import pandas as pd
df = pd.DataFrame({"tags": [["a"], ["b"]]})
shallow = df.copy()
shallow.loc[0, "tags"].append("x") # mutates the list object itself
print(df["tags"].iloc[0]) # ['a', 'x'], the original changed too
df = pd.DataFrame({"tags": [["a"], ["b"]]})
deep = copy.deepcopy(df)
deep.loc[0, "tags"].append("x")
print(df["tags"].iloc[0]) # ['a'], unchangedCopy-on-Write tracks writes to pandas data, such as assigning into a cell. It cannot see you calling append on a list that lives inside a cell. If you store mutable objects in cells, use copy.deepcopy, or better, avoid mutating them in place.
Writing into a NumPy array
Arrays that expose pandas data are read-only under Copy-on-Write. This applies to to_numpy() and .values. If you want to modify the array, make a copy first:
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]) # 1df["a"].to_numpy(copy=True) does the same in one call. Whether to_numpy() returns a view or a new array depends on the dtypes and the memory layout. Do not rely on it, and ask for the copy explicitly whenever you need to write.
This is the one place where a new .copy() may be needed in code that never had one in pandas 2.x. Libraries that modify their input arrays in place (some scikit-learn and SciPy routines, for example) are the usual cause. If one fails with "assignment destination is read-only", copy the array before passing it in.
Releasing a large parent
A derived object can share memory with the object it came from. That is the point of lazy copies. It also means a small slice can keep a large parent's memory alive:
import numpy as np
import pandas as pd
big = pd.DataFrame(np.zeros((1_000_000, 4)), columns=list("abcd"))
head = big.iloc[:10]
print(np.shares_memory(big["a"].to_numpy(), head["a"].to_numpy())) # True
head = big.iloc[:10].copy()
print(np.shares_memory(big["a"].to_numpy(), head["a"].to_numpy())) # False
del big # memory of the large frame can now be freedIf you reduce a large frame to a small result and then discard the large frame, a .copy() on the small result lets Python free the large buffer. This copy is cheap because it only touches the small result, and the saving can be large. Apply it when you have measured a memory problem, not as a default.
Quick reference
| Situation | Keep `.copy()`? | Reason |
|---|---|---|
| `sub = df[df["a"] > 1]`, then modify `sub` | No | `sub` is derived, writes never reach `df` |
| `out = df.reset_index(drop=True)`, then modify `out` | No | Derived object, copied lazily on write |
| Function does `df["x"] = ...` on its argument | Yes, or use `assign` | The parameter is the caller's object |
| `self.data = data`, caller may change `data` later | Yes | Same object under two names |
| Cell values are lists or dicts you mutate in place | Use `copy.deepcopy` | `.copy()` does not copy Python objects in cells |
| Modifying the result of `to_numpy()` or `.values` | Yes, on the array | Array is read-only |
| Small result from a huge frame, huge frame deleted | Yes, once | Frees the parent's memory |
| `.copy()` added to silence `SettingWithCopyWarning` | No | The warning no longer exists |
A safe way to remove copies
Deleting .copy() calls across a codebase is a behavior change if any of them were protecting an aliased object. Work through it in steps:
- Search for
.copy()and group each hit by the table above. - Remove the copies that follow a filter, selection or other method that returns a new object. These are safe.
- For each copy at the top of a function or in a constructor, check whether the code modifies the argument in place. If it does, switch to
assignor another method that returns a new object, or keep the copy. - Run your tests. Add one that passes a frame in, calls the function, and checks that the input is unchanged with
pd.testing.assert_frame_equalagainst a saved copy. - Leave copies that serve the NumPy and memory cases.
Exercise
This function is called as clean(df) and the caller expects df to stay unchanged. Does it need df = df.copy() at the top? Explain, and give a version without the copy.
def clean(df):
df = df.copy()
df = df[df["score"].notna()]
df["score"] = df["score"].clip(0, 100)
return df
Show answer
No. After df = df[df["score"].notna()] the name df refers to a new object derived from the caller's frame, so the later column assignment cannot reach the caller's data. The copy at the top is redundant. Without it: def clean(df): df = df[df["score"].notna()]; df["score"] = df["score"].clip(0, 100); return df. The copy would be needed only if the function assigned to the parameter directly before any derived step, for example df["score"] = ... as its first line.
Exercise
A colleague writes arr = df["price"].to_numpy(); arr[arr < 0] = 0 and gets "assignment destination is read-only". Fix it in two different ways, and say whether df changes.
Show answer
Copy the array before writing: arr = df["price"].to_numpy().copy(), or arr = df["price"].to_numpy(copy=True). Either way df is not changed. If the goal is to update df, skip NumPy and write df.loc[df["price"] < 0, "price"] = 0, or assign the cleaned array back with df["price"] = arr.
Exercise
You build summary = big.iloc[:100] from a 4 GB frame, delete big, and memory use stays high. Why, and what is the smallest change that fixes it?
Show answer
summary is a derived object that can share memory with big, so the large buffer stays alive while summary exists. Change the line to summary = big.iloc[:100].copy(). The copy touches only 100 rows, and after del big the 4 GB buffer can be freed.