skip to content

A pandas script writes a sorted, capped fee Series back with `df.iloc`, and fees land on the wrong payments, while `df.loc` puts them right; why?

level: seniorimportance: should knowfreq 40%

answer

  1. labels versus order on the right side
  2. loc aligns before it writes
  3. iloc and raw arrays ignore labels
  4. missing labels become NaN

basics

~20 s

A .loc write aligns a right-hand Series on its index labels first, so each fee returns to its own payment. iloc ignores labels and writes values in their current order, so a re-sorted Series lands on the wrong rows.

solid answer

~40 s

When the right-hand side of a `.loc` write is a Series or DataFrame, pandas aligns it to the target by labels first. `df.loc[mask, 'fee'] = capped` therefore puts each capped fee on the row with the same `payment_id`, whatever order `capped` is in. `.iloc` works by position and does not align, so after `sort_values` the first value goes to the first selected position, the wrong payment. Passing `capped.to_numpy()` to `.loc` has the same effect, because a raw array carries no labels. Alignment has its own trap: a selected row whose label is missing from `capped` receives NaN, and on an `int64` column that silently widens it to `float64`. The same alignment explains why `df.loc[:, ['B', 'A']] = df[['A', 'B']]` does not swap two columns.

code

python · 18 lines
python
import numpy as np
import pandas as pd

df = pd.DataFrame(
    {"amount": [120.0, 9800.0, 45.5, 15000.0], "fee": [3.0, 25.0, 1.0, 40.0]},
    index=pd.Index([101, 102, 103, 104], name="payment_id"),
)
mask = df["amount"] > 100
capped = df.loc[mask, "fee"].sort_values(ascending=False).clip(upper=30.0)

by_label = df.copy()
by_label.loc[mask, "fee"] = capped
print(by_label["fee"].tolist())   # [3.0, 25.0, 1.0, 30.0]

by_position = df.copy()
pos = np.flatnonzero(mask)
by_position.iloc[pos, by_position.columns.get_loc("fee")] = capped
print(by_position["fee"].tolist())  # [30.0, 25.0, 1.0, 3.0]

go deeper

for a junior

Recall that a loc write matches a Series to rows by index label, while iloc and raw arrays match by position.

for a middle

Explain how alignment happens before the write, why to_numpy disables it, and why the column-swap idiom needs to_numpy to work.

for a senior

Diagnose wrong-row writes by checking for re-ordered right-hand sides and label-free values, and watch for NaN introduced by alignment widening an int column.

for a principal

Favour label-carrying writes as a pipeline rule, and require positional writes to be explicit, so a sort upstream can never move values onto the wrong records.

## Two ways to match values to cells When you assign a single scalar, there is nothing to match: every selected cell gets the same value. When you assign **many values** into **many cells**, pandas has to decide which value goes into which cell. There are two answers: - **By label (alignment).** Each value carries an index label, and it goes to the cell with the same label. - **By position.** The first value goes to the first selected cell, the second to the second, and so on. `.loc` and `.iloc` answer this differently, and that difference is the whole bug. ## What .loc does The pandas indexing guide states it directly: pandas **aligns all axes** when setting a Series or DataFrame through `.loc`. So: ```python capped = df.loc[mask, "fee"].sort_values(ascending=False).clip(upper=30.0) df.loc[mask, "fee"] = capped ``` `capped` is in a different order from `df`, but each value still carries its `payment_id`. Before writing, pandas reindexes `capped` to the selected rows, and every fee returns to its own payment. Order on the right-hand side does not matter. ## What .iloc does `.iloc` addresses cells by position and, as the same guide says, **does not align** a Series or DataFrame on the right. It reads the values in their current order: ```python pos = np.flatnonzero(mask) df.iloc[pos, df.columns.get_loc("fee")] = capped # wrong rows ``` `capped` was sorted by fee, so its first value, the largest fee, is written to the first selected position, which is a different payment. No error is raised: the lengths match, and positions are all `.iloc` checks. ## Other ways to lose the labels | Right-hand side | Matched by | Result after sorting | |---|---|---| | `df.loc[mask, "fee"] = capped` | label | Correct rows | | `df.iloc[pos, j] = capped` | position | Wrong rows | | `df.loc[mask, "fee"] = capped.to_numpy()` | position | Wrong rows | | `df["fee"] = capped` | label | Correct rows; unselected rows become NaN | A NumPy array or a Python list has no labels, so even `.loc` can only use order. Converting to an array is the right move **only** when you want positional matching on purpose. ## The alignment traps Alignment fixes ordering bugs but brings two traps of its own: 1. **Missing labels become NaN.** If a selected row's label is absent from the right-hand Series, that row receives NaN. On an `int64` column this does not raise; NaN introduced this way widens the column to `float64`. 2. **Swapping columns does nothing.** `df.loc[:, ["B", "A"]] = df[["A", "B"]]` aligns the right-hand columns by name, so `B` receives `B` and `A` receives `A`. The indexing guide's fix is to strip the labels with `.to_numpy()`, or to use `.iloc`, which does not align. ## Why pandas aligns on writes at all Alignment exists because labels are the identity of a row in pandas. A Series computed from a frame keeps the frame's index through filtering, sorting and element-wise arithmetic, so the label is the one reliable link back to the original record. Writing by label means a value computed for payment `104` can only ever land on payment `104`, however much the intermediate results were reshuffled. Position, by contrast, is only meaningful while nothing has changed the order. Any of these silently breaks a positional write: - a `sort_values` or `sort_index` between selecting and writing back; - a `dropna` or filter that removed rows from the computed Series; - a result assembled from several pieces in a different order. ## How to diagnose it When values appear on the wrong rows after a write: 1. Check whether the right-hand side was **re-ordered**: `sort_values`, `sort_index`, a groupby result, or a frame built in a different order. 2. Check the **accessor**: `.iloc`, or `.loc` fed a `.to_numpy()`, `.values` or list, matches by position. 3. Check the **labels**: `capped.index.equals(df.index[mask])` tells you whether position and label agree. 4. Prefer label-carrying writes in pipelines, and when the order is meaningful, make it explicit with `reindex` before the write. Alignment in arithmetic and joins as a general idea is covered with pandas axis labels and in the library-neutral material; the point here is that **the accessor you write through decides whether alignment happens at all**.

  • What happens if `capped` lacks one of the labels selected by `mask` in `df.loc[mask, 'fee'] = capped`?
    Alignment gives that row NaN. If `fee` is `float64`, you get a silent missing value. If it is `int64`, the column is widened to `float64` to hold the NaN rather than raising. Check `capped.index` against `df.index[mask]` before the write.
  • How do you swap the values of columns A and B in pandas?
    Strip the labels on the right so `.loc` cannot align them back: `df.loc[:, ['B', 'A']] = df[['A', 'B']].to_numpy()`. Alternatively `df[['A', 'B']] = df[['B', 'A']].to_numpy()`, or write through `.iloc`, which does not align.

Handing back marked exams: .loc returns each paper to the student whose name is on it, so re-sorting the pile by grade changes nothing; .iloc deals the pile out in seat order, so a re-sorted pile lands on the wrong desks.

  • Thinks loc writes a Series in its current order
  • Believes iloc aligns a right-hand Series on its index
  • Passes .to_numpy() to loc and expects label matching
  • Expects df.loc[:, ['B', 'A']] = df[['A', 'B']] to swap columns
  • Assumes a label missing on the right side raises KeyError