compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
Chained assignment vs .locbehaves differently
Mark orders over $100 as priority, then count them.
what differs
orders[mask] makes a new DataFrame, and ["priority"] = True changes that temporary one, so nothing happens to orders. pandas warns about it. .loc[rows, column] selects and assigns in one step on the original.
at a glance
| approach | use it when |
|---|---|
| A · df[mask]["col"] = … | Never: it assigns to a temporary copy. |
| B · df.loc[mask, "col"] = … | Every conditional update: one indexing step on the DataFrame itself. |
Watch out: With pandas' copy-on-write (the default in pandas 3), chained assignment never works, so the habit of .loc is essential.
the outputs
Each approach runs on the same input.
concepts
copy-on-write.locSettingWithCopy
learn it
related comparisons