Sub topic 13
Copies, views, and avoiding chained assignment
This chapter assumes you can select with loc and boolean masks and add columns, as covered in earlier chapters. Here you learn when a change to one object also changes another, and how to write assignments that always land where you intend.
Copies and views
A copy has its own data. A view shares data with another object, so a write through one shows up in the other. Older pandas versions made this hard to predict: whether a selection was a view or a copy depended on the index type, the dtypes, and the selection method.
pandas 3.0 and later use copy-on-write. Every result of an indexing operation behaves as an independent copy, and pandas delays the real copying until you write. In pandas 2.x you can opt in with pd.options.mode.copy_on_write = True. This chapter assumes that behavior, and the advice also holds on older versions.
What chained assignment is
Chained assignment uses two indexing steps in a row, then assigns to the result:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
df[df["pop_m"] > 3]["region"] = "BIG" # chained: does not change df
print(df["region"].tolist()) # ['EU', 'SA', 'AS', 'EU']The first step, df[mask], builds a new temporary DataFrame. The second step assigns into that temporary object, and pandas then discards it. Depending on your version, you get a ChainedAssignmentError or a SettingWithCopyWarning. Either way, df is unchanged.
The fix: one `loc` call
Put the row selector and the column selector in a single loc. pandas then writes into df directly:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
df.loc[df["pop_m"] > 3, "region"] = "BIG"
print(df["region"].tolist()) # ['EU', 'BIG', 'BIG', 'EU']Working on a subset deliberately
Sometimes you want a separate table to modify freely. Call .copy() to say so explicitly. This also silences warnings that come from modifying something pandas treats as a slice of another frame.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
big = df.loc[df["pop_m"] > 3].copy()
big["flag"] = True
print(list(df.columns)) # ['city', 'pop_m']
print(list(big.columns)) # ['city', 'pop_m', 'flag']Common errors
| Pattern | Problem | Use instead |
|---|---|---|
| `df[mask]["col"] = v` | Writes to a temporary object | `df.loc[mask, "col"] = v` |
| `sub = df[mask]; sub["col"] = v` | Ambiguous whether `df` should change | `sub = df[mask].copy()` |
| `df["col"][mask] = v` | Chained, same problem | `df.loc[mask, "col"] = v` |
Exercise
A colleague writes df[df["region"] == "EU"]["pop_m"] = 0 to zero out the population of European cities, and df does not change. Why does that happen, and what is the correct line?
Show answer
The code has two indexing steps. df[df["region"] == "EU"] creates a temporary DataFrame, and the assignment writes into that temporary object, which is then discarded. The correct line is df.loc[df["region"] == "EU", "pop_m"] = 0, which selects rows and column in one call and writes into df.