Sub topic 12
Assigning to selections and avoiding chained indexing
This chapter assumes you can build a DataFrame, use .loc with labels, and build boolean masks. It uses the df of five cities from earlier chapters.
Selecting and assigning in one step
Reading data and writing data both use .loc. If you put a row mask and a column label on the left side of =, pandas changes the original DataFrame.
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"],
)
df.loc[df["continent"] == "Asia", "population_k"] = 3200
print(df.loc[["c"], ["city", "population_k"]])Only Pune is in Asia, so only its population_k changes to 3200. The mask picks the rows and the label picks the column. pandas then writes into the original object in one operation.
What chained indexing is
Chained indexing means two lookups in a row, such as df[mask]["population_k"]. Each pair of brackets is a separate call. The first call can return a copy of the data, so an assignment through the second call may land on a temporary object that is thrown away.
# Avoid: two separate lookups
df[df["continent"] == "Asia"]["population_k"] = 3200Depending on your pandas version, this line raises a SettingWithCopyWarning or does nothing without any message. In pandas 3.0 and later, Copy-on-Write is the default, so a chained assignment never changes df. In either case, do not rely on it.
Making an independent subset
Sometimes you want a smaller table to work on without touching df. Call .copy() when you create it. The subset is then its own object, and you can add columns to it without a warning.
large = df.loc[df["population_k"] > 3000].copy()
large["rank"] = large["population_k"].rank(ascending=False)
print(large)Without .copy(), pandas cannot tell whether you meant to modify df or only the subset. Older versions often raise SettingWithCopyWarning in this case.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `df[mask]["col"] = v` | Warning or silent no-op | `df.loc[mask, "col"] = v` |
| `sub = df[mask]` then `sub["new"] = v` | Warning, unclear intent | `sub = df.loc[mask].copy()` |
| `df.loc[mask]["col"] = v` | Same chained problem | Put the column inside `.loc` |
| Assigning with a mask that has the wrong length | `ValueError` or misaligned rows | Build the mask from the same DataFrame |
A good rule is that the left side of an assignment should contain exactly one indexing step. If you see two sets of brackets before the =, rewrite it.
Exercise
You want to set population_k to 0 for every city in Africa. Write the line, and say why df[df["continent"] == "Africa"]["population_k"] = 0 is unsafe.
Show answer
Use df.loc[df["continent"] == "Africa", "population_k"] = 0. The chained version first creates a filtered object, which may be a copy, and then assigns into it. The original df may stay unchanged, and pandas may only warn or may say nothing at all.