Sub topic 1
The problem: was that a view or a copy?
Before pandas 3, you often couldn't tell whether changing a DataFrame you had just derived would also change the original. This chapter shows where that ambiguity came from and why it caused bugs. The rest of the tutorial covers the fix, which is Copy-on-Write.
Prerequisites
This chapter assumes you know:
- How to create DataFrames and Series and select columns and rows.
- The basics of
.locand.iloc. - That Python objects are mutable and that two names can refer to the same object.
- Roughly what a NumPy array is. This helps but isn't required.
Two words that were never precise
A view is an object that reads the same memory as another object. Changing one changes the other. A copy has its own memory. Changing it leaves the original alone.
Python itself doesn't have this problem for lists, because b = a[:] always copies. NumPy does have views, but its rules are documented: basic slices are views and fancy indexing returns copies. In pandas 2.x and earlier, the result of an indexing operation could be either, and the rule depended on internal details.
The same-looking code, different results
Look at this snippet.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
col = df["a"]
col.iloc[0] = 100
print(df["a"].iloc[0]) # pandas 2.x: 100, pandas 3: 1In pandas 2.x, df["a"] returned a view, so writing to col changed df. In pandas 3, col is independent and df keeps its value of 1.
Whether you got a view depended on things you could not see in the code:
| Operation | Result in pandas 2.x |
|---|---|
| `df["a"]` | Usually a view of the column |
| `df[["a", "b"]]` (list of labels) | A copy |
| `df.iloc[0:2]` (row slice) | A view if the data sits in one block of memory |
| `df.iloc[[0, 1]]` (list of positions) | A copy |
| `df[df["a"] > 1]` (boolean mask) | A copy |
| Any of the above on mixed-dtype columns | Could change from view to copy |
pandas stores columns of the same dtype together in blocks. A slice might be a view when all columns shared one dtype, and a copy once you added a string column. Adding a column elsewhere in the program could therefore change what an unrelated line did.
SettingWithCopyWarning
pandas tried to help by tracking some results as possible copies. If you assigned into one, it raised SettingWithCopyWarning. The warning was a heuristic. It had both false positives, where the code was fine, and false negatives, where the code silently did nothing.
The classic case is chained assignment, which means indexing twice in one statement:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
df[df["foo"] > 1]["bar"] = 100
print(df)The first step, df[df["foo"] > 1], builds a new DataFrame from a boolean mask. In pandas 2.x that was a copy, so the assignment ["bar"] = 100 changed a temporary object that was thrown away. df stayed the same and you got the warning, if you were lucky. With a plain slice in place of the mask, the same pattern could update df, so people learned it as if it were reliable.
Why this was a real cost
The ambiguity caused several problems:
- Silent wrong results. Code that updated the original in tests could stop doing so after a dtype change, with no error.
- Defensive
.copy()calls. Developers added.copy()everywhere "just in case". This used memory and time, and it still didn't prove that other code was safe. - Hard-to-read code. You had to know pandas internals to predict whether
df2 = df[...]was linked todf. - Unreliable warnings. Because
SettingWithCopyWarningwas a heuristic, people learned to ignore it or suppress it.
What pandas 3 changes
pandas 3 removes the ambiguity with one rule. Every DataFrame or Series derived from another object behaves as an independent copy. Changing the derived object never changes the original, and the reverse holds too. To avoid making real copies all the time, pandas delays the actual copy until a write happens. The next chapter states this rule in full.
Code that relied on a view to update a parent object will now behave differently. It may also hide a bug, because it used to work only by accident. The later chapters show how to write those updates in a form that works the same everywhere.
Exercise
In pandas 2.x, df[["a", "b"]] returned a copy, while df["a"] usually returned a view. Why was that a problem when you wrote sub = df[...] and then modified sub? What happens in pandas 3?
Show answer
You couldn't tell from the code whether modifying sub would also change df. The answer depended on the kind of indexer and on how pandas stored the data internally, so a small change elsewhere could change the outcome without any error. In pandas 3, sub is always independent, so modifying it never changes df.