In pandas, what happens when `df.loc` assigns to a row or column label that does not exist yet, and why can't `iloc` do that?
answer
- a missing label on write
- append by label, never by position
- one value per column for a row
- unfilled cells become NaN
- iloc raises IndexError
basics
~20 sWriting to a missing label through loc enlarges the frame: a new row or column is added, unfilled cells become NaN and int64 columns can widen to float64. iloc and iat are positional, so a position past the end raises IndexError.
solid answer
~40 spandas calls this **setting with enlargement**. `df.loc[:, 'net'] = ...` or `df['net'] = ...` adds a column; `df.loc[105] = [60.0, 2.0, 'FR']` adds a row labelled 105 and needs one value per column, or it raises `ValueError: cannot set a row with mismatched columns`. A partial write such as `df.loc[105, 'amount'] = 60.0` adds the row and fills every other cell with NaN, so an `int64` column like `fee` becomes `float64`. `df.at` enlarges the same way. `iloc` and `iat` address positions, and a position past the end does not exist, so they raise `IndexError` (`iloc cannot enlarge its target object`). Each new row rebuilds the frame, so appending in a loop is slow; collect rows and build the frame once.
code
python · 17 linesimport pandas as pd
payments = pd.DataFrame(
{"amount": [120.0, 98.0], "fee": [3, 25]},
index=pd.Index([101, 102], name="payment_id"),
)
payments["net"] = payments["amount"] - payments["fee"] # new column
print(payments["fee"].dtype) # int64
payments.loc[104, "amount"] = 75.0 # new row, partial
print(payments)
print(payments["fee"].dtype) # float64: row 104 has NaN in fee
try:
payments.iloc[len(payments), 0] = 1.0
except IndexError as err:
print(err) # iloc cannot enlarge its target objectgo deeper
Recall that writing to a new label with loc or [] adds a row or column, and that iloc cannot add anything.
Explain the row rules: one value per column or a ValueError, NaN in unfilled cells, and the int64 to float64 change that follows.
Spot row-by-row enlargement in a loop as a quadratic cost and replace it with one build from collected records; check dtypes and the index after any enlargement.
Treat enlargement as an exception path in pipelines: rows arrive by building or combining frames, so the index and dtypes are decided once, not by whichever row came first.
## What setting with enlargement is Most writes in pandas change cells that already exist. **Setting with enlargement** is the case where the label you write to is not there yet. Instead of raising, label-based setters **add** it: - `df["net"] = df["amount"] - df["fee"]` adds a column named `net`. - `df.loc[:, "net"] = ...` does the same through `.loc`. - `df.loc[105] = [60.0, 2.0, "FR"]` adds a row whose index label is `105`. - `df.loc[105, "amount"] = 60.0` adds row `105` and sets one cell of it. - `df.at[106, "fee"] = 1.5` adds row `106` too: when `at` cannot find the label it falls back to the `.loc` path. - On a Series, `s.loc["new"] = value` appends one element. Reading a missing label with `.loc` raises `KeyError`; only **writing** enlarges. ## Rules for a new row A new row needs a value for every column, and the right-hand side decides how it is matched: | Right-hand side | Result | |---|---| | A list with one value per column | Values matched to columns in order | | A list of the wrong length | `ValueError: cannot set a row with mismatched columns` | | A scalar such as `0` | Broadcast to every column | | A Series or dict keyed by column | Matched by column label; missing keys become NaN | When only some cells of the new row are written, as in `df.loc[105, "amount"] = 60.0`, every other cell in that row is **NaN**. A column that cannot hold NaN changes dtype to make room, which is why an `int64` `fee` column turns into `float64` after the row is added. Enlargement is not an in-place write into existing storage, so it widens the column instead of raising the error an in-place write of an incompatible value would raise. ## Why iloc and iat refuse `iloc` and `iat` address cells by **integer position**, from `0` to `len(df) - 1`. Position `len(df)` does not exist, and there is no label to give a row created from a position, so pandas refuses rather than guess: 1. `df.iloc[len(df), 0] = 1.0` raises `IndexError: iloc cannot enlarge its target object`. 2. `df.iat[9, 1] = 2` on a four-row frame raises `IndexError` with an out-of-bounds message. 3. The same holds for a column position past the last column. So the choice of accessor is also a choice about growth: **labels can grow the frame, positions cannot**. ## The same rules on a Series A Series has one axis, so enlargement there means **appending one element**: - `s.loc["new_label"] = 4.5` adds an element with that label. - If the Series held integers, the appended `4.5` widens it to `float64`; enlargement builds new storage, so it widens instead of raising. - `s.iloc[len(s)] = 4.5` raises `IndexError`, for the same reason as on a DataFrame. Whether an integer key in `s[key] = value` means a label or a position is a separate question, covered with label and position access; with `.loc` there is no ambiguity, because the key is always a label. ## The cost of growing row by row Adding a column is cheap compared with adding a row. A new row cannot be slotted into the existing column arrays; pandas builds a new frame that holds the old data plus the row, which copies everything already there. A loop of `df.loc[next_id] = row` therefore copies the whole frame on every iteration, and the total work grows with the square of the row count. Better patterns for many rows: - Collect the rows in a Python list of dicts and build one DataFrame at the end. - Build each batch as its own frame and combine them once; combining frames is covered with pandas merge, join and concat. - Keep `.loc` enlargement for the occasional single row, such as a manual correction or a totals line. ## Checks worth making after an enlargement - **The index:** `df.loc[len(df)] = ...` only makes sense on a default `RangeIndex`. On a `payment_id` index it invents a payment ID that merely equals the row count. - **The dtypes:** compare `df.dtypes` before and after, because a partly filled row turns integer columns into `float64` and can turn a text column into `object` when a non-string lands there. - **Duplicates:** writing to a label that already exists overwrites that row instead of adding one; enlargement happens only when the label is missing.
- Why does `df.loc[len(df)] = row` misbehave on a frame indexed by payment ID?`len(df)` is a row count, not a free label. On a `RangeIndex` it happens to be the next label, so the idiom appends. On a `payment_id` index it either invents an ID equal to the row count or, if that ID already exists, silently overwrites that payment's row instead of adding one.
- How would you add ten thousand rows arriving one at a time from an API?Not with a `.loc` write per row, because each enlargement copies the whole frame. Append each record to a Python list, then build one DataFrame from the list at the end, or build a frame per batch and combine the batches once.
- Expects df.iloc[len(df)] = row to append a row
- Thinks a write to a missing label raises KeyError
- Assumes a partly filled new row keeps int64 columns as int64
- Appends thousands of rows with df.loc in a loop
- Uses df.loc[len(df)] on a frame indexed by IDs