In pandas, why does emp.loc[[1007, 9999]] raise KeyError when only 9999 is missing, and how do you keep the IDs that exist?
answer
- one absent label sinks the list
- no silent NaN rows since 1.0
- intersect with the index first
- reindex when you want the gaps
basics
~20 sSince pandas 1.0, loc with a list raises KeyError if any label is absent rather than returning NaN rows. Keep the present IDs with emp.loc[emp.index.intersection(ids)], or use emp.reindex(ids) when you want NaN rows for the missing ones.
solid answer
~40 s`loc` with a list is strict: if any requested label is absent it raises `KeyError: '[9999] not in index'`, and if none is present the message is `None of [...] are in the [index]`. Before pandas 1.0 a list with missing labels returned NaN rows for them; that was deprecated in 0.21 and removed in 1.0. Two idioms replace it. `emp.loc[emp.index.intersection(ids)]` keeps only the labels that exist and preserves the column dtypes, but returns rows in the frame's own order, not the order of `ids`. `emp.reindex(ids)` returns exactly the requested labels in the requested order with NaN rows for the missing ones, which turns an `int64` column into `float64` unless you pass `fill_value`. Columns follow the same rule: `emp[['name', 'bonus']]` raises `KeyError` naming `bonus`.
code
python · 17 linesimport pandas as pd
emp = pd.DataFrame(
{"name": ["Ana", "Ben", "Cho"], "salary": [52000, 81000, 77000]},
index=pd.Index([1042, 1007, 1311], name="emp_id"),
)
ids = [1311, 9999, 1007]
try:
emp.loc[ids]
except KeyError as err:
print("KeyError:", err)
print(emp.loc[emp.index.intersection(ids)]) # only present IDs, index order
print(emp.reindex(ids)) # every ID, NaN where missing
print(emp.reindex(ids)["salary"].dtype)
print(pd.Index(ids).difference(emp.index).tolist()) # what was missinggo deeper
Recall that one missing label in a list makes loc raise KeyError, and that the error message names the missing labels.
Explain the two replacements: intersection keeps matches with dtypes intact but in index order; reindex returns every requested label in order with NaN rows and an int-to-float upcast unless fill_value is given.
Show where each belongs in a pipeline: KeyError as a guard at an input boundary, intersection plus a logged difference when stale IDs are expected, reindex when the output contract is one row per request.
Frame it as a data-contract decision: whether a missing key should stop a job, be dropped and counted, or be filled, and making that choice explicit rather than leaving it to whichever call someone typed.
## Strict list lookups `DataFrame.loc` and `Series.loc` raise `KeyError` when **any** label in a list is not in the index. Given an employee table indexed by IDs and a list of IDs to look up — say from a request or another system — one stale ID is enough to fail the whole selection: ```python emp.loc[[1007, 9999]] # KeyError: '[9999] not in index' emp.loc[[9998, 9999]] # KeyError: "None of [Index([9998, 9999], dtype='int64', name='emp_id')] are in the [index]" ``` This was a deliberate change. Up to pandas 0.20, a list with missing labels "would always succeed, returning NaN for missing labels", in the words of the 0.21 release notes, which deprecated it; pandas 1.0 removed the reindexing path, so `loc` with list-like indexers and missing labels "will no longer reindex". The reasoning is that a silent NaN row hides a data problem, such as an ID that was never loaded or a key in the wrong dtype, until it surfaces far downstream. ## The two error messages The message tells you how much of the list was missing: - **Some labels missing** — `KeyError: '[9999] not in index'` lists only the absent labels, so you can log them. - **All labels missing** — `None of [Index([...])] are in the [index]` (or `[columns]` on the column axis) often means the whole list has the wrong type, for example string IDs `"1007"` looked up in an integer index. A scalar behaves the same way: `emp.loc[9999]` raises `KeyError: 9999`. Positional lookups fail differently: `emp.iloc[[0, 5]]` on a three-row frame raises `IndexError: positional indexers are out-of-bounds`. ## Keeping the labels that exist The idiomatic filter, recommended in the user guide as "idiomatic and efficient", is to intersect the request with the index first: ```python present = emp.index.intersection(ids) emp.loc[present] ``` - It **preserves dtypes**, because no missing rows are introduced. - It returns rows in the **index's order**, not the order of `ids`: `Index.intersection` keeps the calling index's order, so ask for `[1500, 1007]` and you get 1007 first if that is how the frame is stored. - The complement is one call away: `pd.Index(ids).difference(emp.index)` lists the IDs that were missing, which belongs in a log or a data-quality metric. A boolean mask, `emp.loc[emp.index.isin(ids)]`, selects the same rows; masks are a separate topic. ## Getting a row for every requested label When the output must have exactly one row per requested ID, in the requested order, the method is `reindex`: 1. `emp.reindex([1311, 9999])` returns two rows, the second filled with NaN. 2. Because NumPy `int64` cannot hold NaN, an integer column such as `salary` becomes **`float64`**; text columns hold NaN as their missing value. 3. `emp["salary"].reindex([1311, 9999], fill_value=0)` keeps `int64` by filling with a value instead of NaN. 4. `reindex` raises `ValueError: cannot reindex on an axis with duplicate labels` when the frame's index has duplicates; intersect first, then reindex, if you must. `reindex` itself — aligning to a new set of labels — is covered with axis labels and alignment; here it is the deliberate replacement for the old lenient `loc`. ## Columns follow the same rule The strictness is not specific to rows. `emp[["name", "bonus"]]` and `emp.loc[:, ["name", "bonus"]]` both raise `KeyError: "['bonus'] not in index"` when there is no `bonus` column. For a single optional column, `DataFrame.get("bonus", default)` returns the default instead of raising, and `emp.columns.intersection([...])` filters a list of names the way the index intersection filters IDs. ## Choosing | Goal | Call | Missing labels | Order | Dtypes | |---|---|---|---|---| | Fail fast on bad input | `emp.loc[ids]` | `KeyError` | as requested | kept | | Keep only matches | `emp.loc[emp.index.intersection(ids)]` | dropped | index order | kept | | One row per request | `emp.reindex(ids)` | NaN rows | as requested | int becomes float | | One row per request, typed | `reindex(ids, fill_value=0)` | filled | as requested | kept | The `KeyError` is usually the right default in a pipeline: it stops bad input at the boundary. Choose a lenient form only when missing IDs are expected, and log what was dropped or filled. ## Mistakes interviewers listen for - Claiming `loc` returns NaN rows for missing labels, which stopped in pandas 1.0. - Wrapping the lookup in `try`/`except KeyError` and returning nothing, which drops the IDs that did exist. - Forgetting that `reindex` turns an integer column into `float64` unless `fill_value` is given. - Using `emp.iloc[ids]` with IDs, which reads them as positions.
- Why did emp.loc[emp.index.intersection([1311, 1007])] return 1007 before 1311?`Index.intersection` keeps the order of the calling index, and in this frame 1007 is stored before 1311. The filter answers 'which of these exist', not 'in which order'. If the request's order matters, filter the list instead: `emp.loc[[i for i in ids if i in emp.index]]` keeps the order of `ids`, or call `reindex(ids)` and accept NaN rows.
- A lookup of string IDs ['1007', '1311'] raises 'None of [...] are in the [index]' although both employees exist. What is wrong?The index holds integers and the request holds strings, so no label matches and pandas reports that none were found. Convert the request to the index's dtype first, for example `[int(i) for i in ids]` or `pd.Index(ids).astype(emp.index.dtype)`, then select. The all-missing message is the usual sign of a type mismatch rather than stale data.
- Does reindex work when the employee index has duplicate IDs?No. `reindex` raises `ValueError: cannot reindex on an axis with duplicate labels`, because it cannot decide which duplicate a requested label maps to. Select the matches first with `emp.loc[emp.index.intersection(ids)]`, which accepts duplicates, or de-duplicate the index before reindexing.
- loc with a list returns NaN rows for labels it cannot find.
- A KeyError from loc means every requested label was missing.
- emp.index.intersection(ids) returns rows in the order ids lists them.
- reindex keeps an int64 column as int64 when some labels are missing.
- emp[['name', 'bonus']] skips the unknown column and returns name.