In pandas, how does `DataFrame.update` write corrected values from another frame, and what does it leave untouched?
answer
- match on both axes
- missing values never overwrite
- left side keeps its shape
- modifies the caller, returns nothing
basics
~20 sDataFrame.update aligns the other frame on index and column labels and overwrites the caller's matching cells with the other frame's non-NA values, in place, returning None. NaN in the other frame never overwrites, and unmatched rows or columns are ignored.
solid answer
~40 s`payments.update(corrections)` matches `corrections` to `payments` by index label and column label, then writes every non-NA value from `corrections` into the matching cell of `payments`. It changes `payments` in place and returns `None`. A NaN in `corrections` means "no correction", so the original value survives. Rows or columns that exist only in `corrections` are ignored: `update` never adds rows or columns, and `join='left'` is the only join it implements. `overwrite=False` writes only into cells that are NA in `payments`; `errors='raise'` raises `ValueError` when both frames hold non-NA data in the same cell; `filter_func` limits which original values may be replaced. Duplicate labels in `corrections` raise `ValueError`. A Series works too, if its `name` is the target column.
code
python · 21 linesimport numpy as np
import pandas as pd
payments = pd.DataFrame(
{"amount": [120.0, 9800.0, 45.5], "fee": [3.0, 25.0, 1.0]},
index=pd.Index([101, 102, 103], name="payment_id"),
)
corrections = pd.DataFrame(
{"fee": [20.0, np.nan, 5.0], "status": ["ok", "ok", "ok"]},
index=[102, 103, 999],
)
result = payments.update(corrections)
print(result) # None
print(payments["fee"].tolist()) # [3.0, 20.0, 1.0]
print(payments.columns.tolist()) # ['amount', 'fee']
try:
payments.update(corrections, errors="raise")
except ValueError as err:
print(err) # Data overlaps.go deeper
Recall that update writes non-missing values from another frame into matching cells of the caller and returns None.
Explain the label alignment on both axes, why NaN never overwrites, why unmatched labels vanish, and what overwrite, errors and filter_func change.
Check the overlap between the two indexes before patching, because a correction for an unknown ID is dropped without an error; use errors='raise' for fill-only jobs.
Decide whether patches are applied with update or by rebuilding the frame from sources, so corrections are auditable and dropped ones are reported rather than lost.
## What update is for `DataFrame.update` applies **patches**: a smaller frame of corrected values is written over a larger frame, cell by cell, wherever the two share a row label and a column label. A typical case is a payments table indexed by `payment_id` and a corrections frame from a reconciliation job, indexed the same way, holding new `fee` values for a few payments. ```python payments.update(corrections) ``` ## How it decides what to write The steps, as the implementation performs them: 1. **Check `other`.** Anything that is not a DataFrame is converted to one; a Series must have its `name` set, because the name is used as the column label. Duplicate index labels in `other` raise `ValueError`. 2. **Align rows.** Only labels present in **both** indexes take part. Rows found only in `other` are dropped from consideration; rows found only in the caller are left alone. If no labels overlap, the call returns without changing anything. 3. **Align columns.** Only columns present in both frames are processed. A column that exists only in `other` is **not** added. 4. **Pick cells.** For each shared column, a cell is written when the value in `other` is **not NA** (with the default `overwrite=True`). 5. **Write.** The chosen values are written into the caller through a label-based assignment, column by column. The result keeps the caller's index, columns and length. The docstring says it plainly: the DataFrame's length does not increase. ## A worked reconciliation Take `payments` with fees `3.0`, `25.0` and `1.0` for payments `101`, `102` and `103`, and `corrections` holding fee `20.0` for `102`, NaN for `103`, `5.0` for `999`, plus a `status` column. After `payments.update(corrections)`: - **101** keeps `3.0`: there is no correction row for it. - **102** becomes `20.0`: both frames have the label and the correction is not NA. - **103** keeps `1.0`: its correction is NaN, which means "leave it". - **999** is ignored: `payments` has no such payment, and no row is added. - **status** is ignored: `payments` has no such column, and no column is added. So one value changed, and nothing reports that two pieces of the corrections frame were discarded. That silence is the main operational risk of `update`. ## The parameters | Parameter | Default | Effect | |---|---|---| | `join` | `'left'` | The only option implemented; anything else raises `NotImplementedError` | | `overwrite` | `True` | `True`: overwrite with every non-NA value from `other`. `False`: write only where the caller is NA | | `filter_func` | `None` | A callable on the caller's column values, returning True where replacement is allowed | | `errors` | `'ignore'` | `'raise'`: raise `ValueError("Data overlaps.")` if both frames hold non-NA data in the same cell | `errors="raise"` is the guard for "fill, never overwrite" jobs: it refuses to run rather than silently replacing a value that already exists. ## What it leaves untouched - **Cells where `other` is NA.** NaN in the corrections frame means "no correction here", not "set to missing". To blank a value on purpose, use a `.loc` write instead. - **Rows and columns not in both frames.** No enlargement happens, so a correction for an unknown `payment_id` disappears without an error. Check the overlap first if that matters, for example with `corrections.index.difference(payments.index)`. ## Return value and style `update` has **no `inplace` keyword**. It always modifies the caller and returns `None`, so `payments = payments.update(corrections)` replaces the frame with `None`. Call it as a statement. To patch one column from a Series, name the Series after that column: `payments.update(fixes.rename("fee"))`. ## When to use something else - To **combine** two sources into a new frame where either may fill gaps, use `combine_first`, which returns a new object. - To **add** new rows from the corrections, combine the frames instead; that is covered with pandas merge, join and concat. - For a single conditional rule, a masked `.loc` write is clearer than building a patch frame.
- How do you fill only the gaps in `payments` from `corrections`, never replacing an existing value?Call `payments.update(corrections, overwrite=False)`. pandas then writes a value from `corrections` only where the matching cell in `payments` is NA. To fail loudly when both frames hold a value for the same cell, use `errors='raise'` instead, which raises `ValueError` on any overlap.
- How would you set a fee back to missing through `update`?You cannot: a NaN in the other frame is read as "no correction" and skipped. Clear the cell with a label-based write such as `payments.loc[103, 'fee'] = np.nan` instead.
- Expects NaN in the corrections frame to blank the original value
- Thinks update appends corrections whose labels are missing
- Writes payments = payments.update(corrections) and expects a frame back
- Believes update matches rows by position
- Expects update to add columns that only the other frame has