Sub topic 3
Assigning values safely with .loc and .iloc
This chapter assumes you know how to create DataFrames and Series, select columns and rows, and use .loc and .iloc for reading. It also assumes you know that Python objects are references to mutable data. Under Copy-on-Write (CoW), the only behavior in pandas 3, one rule governs everything here: a DataFrame or Series derived from another object never changes the object it came from.
What the rule means for assignment
Selecting a column, filtering rows, or calling a method such as reset_index gives you a new object. Writing to that new object changes only that object. The original stays as it was.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
col = df["a"]
col.iloc[0] = 100
print(col.iloc[0]) # 100
print(df["a"].iloc[0]) # 1, df is unchangedcol came from df, so changing col does not touch df. Before pandas 3, whether this worked depended on internal details. Now the outcome is the same every time.
The consequence is simple. To change df, you must write to df itself, in one step, with an indexer on df.
Writing to df in one step
.loc selects by label and .iloc selects by integer position. Both work as the target of an assignment. When you write df.loc[row, column] = value, pandas receives the whole request at once and updates df directly.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df.loc[0, "a"] = 100 # by label
df.iloc[1, 1] = 50 # by position
print(df)The output is:
a b
0 100 4
1 2 50
2 3 6Choose .loc when you know the labels and .iloc when you know the positions. If the index is a default RangeIndex, labels and positions match, which is why df.loc[0, "a"] and df.iloc[0, 0] hit the same cell here. They differ after you filter, sort, or set a custom index.
Updating selected rows with a boolean mask
A common task is to change one column only for rows that meet a condition. Put the mask in the row position and the column label in the column position of a single .loc call.
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
df.loc[df["foo"] > 1, "bar"] = 100
print(df)The mask df["foo"] > 1 is a Series of booleans. It is False, True, True here, so rows 1 and 2 receive the new value in bar. Row 0 keeps its old value.
foo bar
0 1 4
1 2 100
2 3 100You can assign a single value, as above, or a list, array, or Series of matching length. A Series aligns on the index, so values go to matching labels, not to matching positions.
Why the single call matters
Consider the two-step version. It looks reasonable, and it used to work in some situations.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
# Chained assignment: modifies a temporary object and emits a ChainedAssignmentError warning.
df["a"][0] = 100
print(df["a"].iloc[0]) # 1, df is unchanged
# Single-step assignment with .loc updates df itself.
df.loc[0, "a"] = 100
print(df["a"].iloc[0]) # 100In df["a"][0] = 100, Python first evaluates df["a"]. That produces a derived Series. The assignment then writes into that Series. By the CoW rule, the write cannot reach df, so the value is lost. pandas warns you with a ChainedAssignmentError. The .loc version has no intermediate object, so the write lands on df.
The sequence below shows the difference.
A quick checklist
Use this when you write any assignment into an existing DataFrame.
- Start the left-hand side with the DataFrame name, such as
df.loc[...]ordf.iloc[...]. - Put both the rows and the columns inside one pair of brackets.
- Use a boolean mask for the rows when the update depends on a condition.
- Use
.locfor labels and.ilocfor positions. Do not mix them in one call.
Common mistakes
- Assigning to a selection you stored in a variable and expecting
dfto change. The variable holds a derived object. - Using
.ilocwith a boolean Series. Use.locwith a Series mask, or passmask.to_numpy()to.iloc. - Assuming labels equal positions after filtering. Check which indexer you need.
Exercise
Given df = pd.DataFrame({"price": [10, 20, 30], "tax": [1, 2, 3]}), write one statement that sets tax to 0 for every row where price is greater than 15. Then explain why df[df["price"] > 15]["tax"] = 0 would leave df unchanged.
Show answer
df.loc[df["price"] > 15, "tax"] = 0 updates rows 1 and 2 of df. The chained version first builds df[df["price"] > 15], a derived DataFrame, then selects "tax" from it, a second derived object. The assignment writes to that last object. Under Copy-on-Write, derived objects never change the object they came from, so df is untouched and pandas emits a ChainedAssignmentError warning.