Sub topic 12
Assigning to selections and avoiding chained indexing
This chapter assumes you can build a DataFrame from a dictionary and that you know .loc, .iloc, and boolean masks from the earlier chapters. It also assumes you have pandas installed and imported as pd. Here you will learn how to write values back into a DataFrame through a selection. You will also learn why one common style of doing it fails.
The setup
The examples reuse the small city table with a string index.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)Selection can return a view or a copy
When you select data, pandas returns one of two things:
- A view shares memory with the original DataFrame. Changing the view changes the original.
- A copy has its own memory. Changing it leaves the original alone.
Which one you get depends on the kind of selection and on the pandas version. A boolean mask always produces a copy. Selecting a single column often produces a view in older versions. Slices of rows can go either way. You cannot reliably tell by looking at the code.
This matters because an assignment only reaches df if it is applied to df itself, or to a view of it.
What chained indexing is
Chained indexing means two or more indexing operations in a row, such as df[mask]["col"]. Python runs it as two separate calls:
df[mask]runs first. It returns a new DataFrame, which is a copy.["col"]is then applied to that temporary result.
If the chain ends in an assignment, the write goes to the temporary object and df never sees it:
# Wrong: the assignment targets a temporary copy
df[df["continent"] == "Asia"]["population_k"] = 3200In pandas 2.x without Copy-on-Write, this line usually emits a SettingWithCopyWarning and leaves df unchanged. A variant such as df["population_k"][mask] = 3200 sometimes works, because the column can be a view. That inconsistency is the real hazard. The same pattern can work on one pandas version or one DataFrame and silently fail on another.
Assigning with one .loc call
The fix is to select and assign in one operation. df.loc[rows, columns] = value is translated into a single __setitem__ call on df, so pandas knows exactly where the write should land.
df.loc[df["continent"] == "Asia", "population_k"] = 3200
print(df.loc[["c"], ["city", "population_k"]])The row for Pune now shows 3200. The first argument is the row selector, which can be a mask, a label, a list of labels, or a slice. The second is the column selector.
You can use the same form to assign to several cells at once, or to create a new column:
# Assign one value to every row the mask selects
df.loc[df["population_k"] > 5000, "size"] = "large"
# Rows outside the mask get NaN in the new column
print(df[["city", "population_k", "size"]])Only Lima and Cairo are labelled large. The other three rows hold NaN, because pandas has to put something in every row of the new column.
Filling in the rest of a new column
Often you want a value for every row. Assign with two masks, or assign a default first and then overwrite part of it:
df["size"] = "small"
df.loc[df["population_k"] > 5000, "size"] = "large"
print(df["size"].tolist())The result is ['small', 'large', 'small', 'large', 'small']. Assigning the default first with df["size"] = ... is safe, because it is a single operation on df.
How values on the right-hand side are aligned
When the right-hand side is a Series, pandas aligns it to the target by index label, not by position. Here, only the rows in the mask are written, and each takes the value with the same label:
bonus = pd.Series({"b": 1, "d": 2})
df.loc[["b", "d"], "population_k"] += bonus
print(df.loc[["b", "d"], "population_k"].tolist())The output is [10093, 10232]. If the labels did not match, the unmatched cells would become NaN. When you assign a plain list or array instead, its length must match the number of selected cells, and it is applied by position.
Two related points:
- With
.iloc, a boolean mask must be a plain array or list, not a Series. Usemask.to_numpy(), since.ilocrejects an indexed Series. - With
.loc, a boolean Series mask is fine, because it is aligned to the index.
Working with an independent subset
Sometimes you want a smaller table to work on without touching the original. Make the independence explicit with .copy():
large = df.loc[df["population_k"] > 3000].copy()
large["rank"] = large["population_k"].rank(ascending=False)
print("rank" in df.columns)
print(large[["city", "population_k", "rank"]])The first print shows False: df has no rank column. Without .copy(), older pandas versions do not know whether large is meant to be a view or a separate table. They emit SettingWithCopyWarning when you add the column, and it is unclear what the write does. Calling .copy() removes the ambiguity.
Copy-on-Write changes the rules
pandas 3.0 makes Copy-on-Write the default. In pandas 2.x you can opt in with pd.options.mode.copy_on_write = True. Under this model:
- Every result of an indexing operation behaves as an independent copy. pandas delays the actual copying until one of the objects is modified, so it is cheap.
- Modifying a selection never changes the original DataFrame.
- Chained assignment such as
df["population_k"][mask] = 3200never works. It emits aChainedAssignmentErrorwarning that says the assignment had no effect. SettingWithCopyWarningno longer exists, because no assignment can be ambiguous.
The consequence is that the single-.loc style is correct under both the old and the new behavior. Code written with .loc and .copy() needs no changes when you upgrade.
| Pattern | pandas 2.x default | With Copy-on-Write |
|---|---|---|
| `df.loc[mask, "col"] = v` | Updates `df` | Updates `df` |
| `df[mask]["col"] = v` | Warns, `df` unchanged | Warns, `df` unchanged |
| `df["col"][mask] = v` | Often updates `df`, with a warning | Warns, `df` unchanged |
| `sub = df[mask]; sub["x"] = 1` | Warns, unclear effect | Changes `sub` only |
| `sub = df[mask].copy(); sub["x"] = 1` | Changes `sub` only | Changes `sub` only |
Common mistakes
- Splitting a chain across lines. Writing
sub = df[mask]and thensub["col"] = vis still chained indexing, only spread over two statements. Pandas may warn about it. - Using
inplace=Trueon a selection.df["col"].fillna(0, inplace=True)operates on a temporary Series. Assign the result back instead:df["col"] = df["col"].fillna(0). - Mixing positions and labels in one chain.
df.iloc[0]["population_k"] = 1first builds a row Series, which may be a copy. Usedf.loc["a", "population_k"] = 1ordf.iloc[0, 2] = 1. - Expecting a mask result to stay linked.
big = df[df["population_k"] > 3000]is a snapshot. Later changes todfdo not reachbig, and changes tobigdo not reachdf. - Using
andandorin the mask. These raise aValueErroron Series. Use&and|, with each comparison in parentheses or in its own variable.
Exercise
The line df[df["continent"] == "Africa"]["population_k"] = 11000 does not reliably change df. Rewrite it so that it does, and say why your version is safe.
Show answer
Use df.loc[df["continent"] == "Africa", "population_k"] = 11000. The original line indexes twice. The first step, df[mask], builds a temporary copy, and the assignment is applied to that copy. The .loc version is one call on df itself that carries both the row mask and the column label, so pandas writes directly into df. It behaves the same with or without Copy-on-Write.
Exercise
You want a table of South American cities that you can add a "share" column to, without changing df. Write the code and say what would go wrong if you left out the last method call.
Show answer
sa = df.loc[df["continent"] == "South America"].copy(); sa["share"] = sa["populationk"] / sa["populationk"].sum(). Without .copy(), older pandas cannot tell whether sa is a separate table or a view of df, so adding the column emits SettingWithCopyWarning and the effect on df is unclear. With .copy() the subset is independent and df is untouched.