Sub topic 1
The problem: was that a view or a copy?
Before pandas 3, you often couldn't tell whether changing a derived DataFrame or Series would also change the original. This chapter explains why that happened, how the old warnings tried to cover for it, and what that costs in real code. The rest of the tutorial covers the replacement: Copy-on-Write (CoW).
Prerequisites
This chapter assumes you can:
- Create DataFrames and Series, and select columns and rows with
[],.locand.iloc. - Read Python code that mutates objects and passes references around. You know that two names can point to the same list.
- Recognize a NumPy array. Deep NumPy knowledge is helpful but not required.
You also need a Python environment with pandas installed. The survey script below runs on pandas 2.x and pandas 3. Its output differs between the two, and that difference is the point of the chapter.
Two kinds of results
When you write df2 = <some operation on df>, pandas can hand you one of two things:
- A view: a new Python object whose data is the same memory as
df. Writing to one changes the other. - A copy: a new object with its own memory. Writing to one leaves the other alone.
The same idea exists in NumPy. Basic slicing returns a view and fancy indexing returns a copy:
import numpy as np
arr = np.array([1, 2, 3, 4])
view = arr[:2] # basic slice: a view
copy = arr[[0, 1]] # list of positions: a copy
view[0] = 100
copy[1] = 200
print(arr) # [100 2 3 4]NumPy's rule is simple enough to memorize. The type of indexing you use decides the result.
pandas had no such rule. Which result you got depended on the operation, the dtypes of the columns, how the data was laid out internally, and sometimes the pandas version. You could not tell from reading the code.
A survey of the old behavior
The script below creates a small DataFrame, derives something from it in several ways, writes to the first value of the derived object, and reports whether the original changed. It runs on both pandas 2.x and pandas 3.
import pandas as pd
def changed_original(derive):
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
derived = derive(df)
if isinstance(derived, pd.Series):
derived.iloc[0] = 100
else:
derived.iloc[0, 0] = 100
return bool(df.iloc[0, 0] == 100)
cases = {
'df["a"]': lambda d: d["a"],
'df[["a", "b"]]': lambda d: d[["a", "b"]],
"df.iloc[:2]": lambda d: d.iloc[:2],
"df.iloc[[0, 1]]": lambda d: d.iloc[[0, 1]],
'df[df["a"] > 0]': lambda d: d[d["a"] > 0],
}
print("pandas", pd.__version__)
for name, derive in cases.items():
print(f"{name:18} modifies original: {changed_original(derive)}")On pandas 2.2 with default settings, this all-integer frame typically gives:
| Expression | Modifies original in pandas 2.x | Modifies original in pandas 3 |
|---|---|---|
| `df["a"]` | True (view) | False |
| `df[["a", "b"]]` | False (copy) | False |
| `df.iloc[:2]` | True (view) | False |
| `df.iloc[[0, 1]]` | False (copy) | False |
| `df[df["a"] > 0]` | False (copy) | False |
The pandas 2.x column has no tidy rule behind it. A single column and a list containing one column are both "select column a". A slice of rows and a list of row positions select the same rows. Yet each pair behaves differently.
Your terminal may also show SettingWithCopyWarning messages on pandas 2.x. The next section explains where they come from.
The pandas 3 column is all False. That is the end state this tutorial builds toward, and the next chapter states the rule behind it.
Why the answer depended on the layout
Internally, pandas 2.x stored a DataFrame's data in blocks. A block is a 2D NumPy array holding all columns of one dtype. An all-integer DataFrame is usually one block.
The block layout made some results naturally views and others naturally copies:
- Selecting one column by label could return a view of one row of the block. pandas also cached that Series on the DataFrame, so repeated
df["a"]calls returned the same object. - A row slice such as
df.iloc[:2]could return views of the blocks, because NumPy slicing is a view. - A list of labels or positions, or a boolean mask, forced a copy. NumPy fancy indexing can't return a view, so pandas gathered the values into new memory.
pandas documented that the result "depends on the memory layout of the underlying array" and advised that you should not rely on it. Code that relied on it anyway worked until the dtypes, the operation, or the pandas version changed.
The same-looking code, different outcomes
The ambiguity was worst for assignment. Consider two ways to say "set b to 100 where a is greater than 1". Both are written as chained assignment, meaning two indexing operations in a row.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df[df["a"] > 1]["b"] = 100 # pandas 2.x: SettingWithCopyWarning, df unchanged
print(df["b"].tolist())
df["b"][df["a"] > 1] = 100 # pandas 2.x: usually works, df changed
print(df["b"].tolist())On pandas 2.x, the first statement filters rows, which makes a copy. Then it assigns into that copy, and the copy is thrown away. The second statement selects the column b, which is a view, and then assigns into it through a boolean mask. That write reaches df.
The two lines differ only in the order of their two operations. One loses the write and the other keeps it. Nothing in the syntax tells you which is which, and a reader who has not memorized the internals can't tell either.
On pandas 3, neither statement changes df. Chapter 4 of this tutorial covers why, and which single-step form to use instead. It also covers the warning pandas 3 emits. For now, note that the old behavior was inconsistent and that the fix was to make every derived object behave the same way.
SettingWithCopyWarning: a heuristic, not a guarantee
pandas 0.13 added SettingWithCopyWarning to catch the worst cases. Each result object carried an internal weak reference to its parent when pandas guessed it might be a copy. If you later wrote to a flagged object, pandas warned you.
This helped, but it had structural limits:
- False positives. Code that was correct often triggered the warning. A common reaction was
pd.options.mode.chained_assignment = None, which silences the check everywhere, including where it was right. - False negatives. Some bugs were never flagged, because the flag was only set on certain code paths. If pandas had not marked the object, a write to a copy passed silently.
- Guesswork on lifetime. The flag was a weak reference. Whether you got a warning could depend on whether the parent had been garbage-collected.
- Misleading advice. The warning text suggested
.locor.copy(), but adding.copy()to silence the warning sometimes just hid a real logic mistake.
The warning was a patch over an unclear data model. A warning can't fix a model in which the result depends on internal layout.
Defensive copies and their cost
Because nobody could be sure what they held, a habit grew. People added .copy() after almost any derivation:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
subset = df[df["a"] > 1].copy() # "just to be safe"
subset["c"] = subset["a"] * 2
print(subset)This is correct code, but it carries two costs:
- Memory and time. Every
.copy()allocates and fills new memory. In a pipeline with many steps on a large frame, these copies add up even where the old code would have been safe without them. - Noise. A reader can't tell which
.copy()calls prevent a real bug and which are superstition.
The reverse failure was worse. Leaving off the .copy() could mean that a later write changed the source frame you thought was untouched. The same question applied to function arguments. Would a function that modifies its argument's column change the caller's DataFrame? On pandas 2.x the honest answer was "sometimes".
Why it could not be fixed incrementally
The pandas developers could have documented a rule for each operation. That would have been a long table and still subject to dtype and layout exceptions. Several things pushed them toward changing the model:
- Predictability. A result that depends on internal layout is not part of a stable public contract.
- Performance. Always copying would be safe but expensive. Always viewing would be fast but lets writes leak. Neither extreme was acceptable on its own.
- Mutation by accident. Many users never intended to modify a parent frame. They got that behavior as a side effect of an operation that happened to return a view.
- Interaction with other libraries. NumPy and other array libraries hold references to pandas data. Whether those references remain valid and writable was undefined.
Copy-on-Write resolves the tension with one rule and a deferred copy. The next chapter states them in full, and a short preview is enough here:
- The rule: every DataFrame or Series derived from another behaves as an independent copy. Modifying it never changes the object it came from, and the reverse holds too.
- The mechanism: pandas does not copy immediately. Derived objects share memory with their parent until one of them is written to, and only then does the written object get its own copy.
The diagram shows the decision a pandas 2.x reader had to make, compared with pandas 3.
Checking which behavior you have
Before you apply anything in the following chapters, confirm which pandas you are running:
import pandas as pd
print(pd.__version__)
major = int(pd.__version__.split(".")[0])
if major >= 3:
print("Copy-on-Write is the only behavior.")
else:
print("Legacy behavior by default. CoW can be opted into.")On pandas 2.x you can opt in to the new behavior to preview it:
import pandas as pd
pd.options.mode.copy_on_write = TrueOpting in is a useful way to find code that depends on the old view behavior before you upgrade. Run your test suite with the option on and read the failures. The final chapter of the tutorial covers migration in detail.
What to take away
- A view shares memory with its parent. A copy does not. pandas 2.x returned either, depending on the operation and internal layout.
- Pairs of expressions that look equivalent, such as
df["a"]versusdf[["a"]], behaved differently. SettingWithCopyWarningwas a best-effort check with both false alarms and silent misses.- Defensive
.copy()calls were a reasonable response, but they cost memory and hid the real data flow. - pandas 3 replaces the guesswork with one rule: derived objects behave as independent copies, and the actual copy is deferred until a write.
Exercise
On pandas 2.x without Copy-on-Write, a colleague writes sub = df[["a", "b"]] and then sub.iloc[0, 0] = 100. Another writes s = df["a"] and then s.iloc[0] = 100. For an all-integer DataFrame, which of the two typically changes df, and what does the same pair of snippets do on pandas 3?
Show answer
On pandas 2.x only the second one typically changes df. The first selects with a list of labels, which forces a copy. The second selects a single column, which returns a view of the column's data. On pandas 3 neither changes df, because every derived object behaves as an independent copy.
Exercise
Why was adding pd.options.mode.chained_assignment = None a poor fix for SettingWithCopyWarning?
Show answer
It disables the check for the whole session. It does not change what the code does, so writes that go to a discarded copy still go nowhere. It also hides the warnings that were correct, so real bugs are no longer reported.
Exercise
A teammate says "In pandas 3, df[df["a"] > 1] makes a full copy of the data every time, so it must be slow." What is wrong with that statement?
Show answer
Under Copy-on-Write, the result behaves as an independent copy, but pandas does not copy the data until one of the two objects is written to. Behaving as a copy and being copied immediately are different things. (A boolean-mask selection gathers the selected rows into new memory regardless, but that is a property of the selection, not of Copy-on-Write.)