skip to content

In pandas, when should you read one cell with DataFrame.at or DataFrame.iat instead of loc and iloc, and what do they reject?

level: middleimportance: should knowfreq 40%

answer

  1. one cell, nothing more
  2. a label pair versus a position pair
  3. less dispatch per call
  4. duplicate labels change the result

basics

~20 s

Use at (labels) or iat (positions) when you want exactly one scalar: they skip the key-type dispatch loc and iloc perform. They reject list-like keys, iat rejects non-integers, and at raises KeyError for a missing label.

solid answer

~40 s

`df.at[row_label, col_label]` and `df.iat[row_pos, col_pos]` are the scalar-only counterparts of `loc` and `iloc`. Because each axis takes exactly one key, they skip the dispatch `loc` and `iloc` run for lists, slices and masks, and the user guide calls them the fastest way to get or set a single value. In return they refuse anything else: `emp.at[[1007], 'salary']` raises (an `InvalidIndexError` on a DataFrame, a `ValueError` on a Series), `emp.iat[1, 'salary']` raises `ValueError: iAt based indexing can only have integer indexers`, a DataFrame needs both keys, and a missing label raises `KeyError`. One edge: when a DataFrame's row or column labels are duplicated, `at` falls back to `loc` and can return a Series. The gain is per call and modest; it does not rescue a Python loop over rows.

code

python · 17 lines
python
import pandas as pd

emp = pd.DataFrame(
    {"name": ["Ana", "Ben"], "dept": ["ops", "eng"], "salary": [52000, 81000]},
    index=pd.Index([1042, 1007], name="emp_id"),
)
print(repr(emp.at[1007, "salary"]))   # by labels
print(repr(emp.iat[1, 2]))            # by positions

for call in (lambda: emp.iat[1, "salary"], lambda: emp.at[9999, "salary"]):
    try:
        call()
    except (ValueError, KeyError) as err:
        print(type(err).__name__, err)

dup = pd.DataFrame({"salary": [81000, 83000]}, index=[1007, 1007])
print(type(dup.at[1007, "salary"]).__name__)   # duplicate labels: falls back to loc

go deeper

for a junior

Recall the pairing: at goes with loc and labels, iat goes with iloc and positions, and both return one value. Know that a DataFrame needs both a row and a column key.

for a middle

Explain why they are faster per call (no key-type dispatch), what each rejects and with which exception, and how duplicate labels make at fall back to loc and return a Series.

for a senior

Show judgment about when the speedup matters: a single-cell lookup on a hot path, yes; a loop over rows, no, vectorise instead. Mention guarding uniqueness where at must yield a scalar.

for a principal

Frame it as code-review guidance: scalar accessors document intent and fail loudly on wrong keys, but a codebase full of at calls in loops signals a design that should be vectorised.

## What at and iat are pandas has two **scalar accessors** beside the general ones: - **`DataFrame.at` / `Series.at`** — a **label**-based lookup of exactly one value, the scalar twin of `loc`. On a DataFrame it takes a row label and a column label: `emp.at[1007, "salary"]`. - **`DataFrame.iat` / `Series.iat`** — a **position**-based lookup of exactly one value, the scalar twin of `iloc`: `emp.iat[1, 2]` is the second row, third column. Both return the bare value, such as `np.int64(81000)`, not a one-cell Series or DataFrame. Both can also set a single value (`emp.at[1007, "salary"] = 83000`); writing values, including the case where `at` enlarges the frame because the label is new, belongs with assigning values. ## Why they exist `loc` and `iloc` accept a scalar, a list, a slice, a boolean array, a callable, or a tuple of those per axis, so every call first works out which kind of key it was given and which result shape to build. The user guide says of `[]` that handling so many cases gives it "a bit of overhead in order to figure out what you're asking for", and that if you only want a scalar the fastest way is `at` or `iat`; `loc` and `iloc` face the same many-cases dispatch. In practice the saving is **per call and modest**, not orders of magnitude. It matters where code genuinely reads or writes individual cells many times, such as a small lookup inside a function called per event. It does **not** make a Python loop over a large frame acceptable: a vectorised column operation replaces thousands of `at` calls with one array operation, and that is the change that matters for speed. ## What they reject The narrow contract is also a safety feature: a call that would silently return a frame through `loc` fails loudly through `at`. | Call (emp has columns name, dept, salary) | Outcome | |---|---| | `emp.at[1007, "salary"]` | the scalar `81000` | | `emp.iat[1, 2]` | the same scalar, by position | | `emp.at[[1007], "salary"]` | `InvalidIndexError` — a list is not a scalar key | | `emp["salary"].at[[1007]]` | `ValueError: Invalid call for scalar access (getting)!` | | `emp.iat[1, "salary"]` | `ValueError: iAt based indexing can only have integer indexers` | | `emp.at[9999, "salary"]` | `KeyError: 9999` | | `emp.iat[5, 0]` on a two-row frame | `IndexError` — position out of bounds | | `emp.at[1007]` | `TypeError` — a DataFrame needs both a row and a column key | Note the last row: unlike `loc`, `at` on a DataFrame cannot return a whole row. ## The duplicate-label edge `at` promises a scalar only when the labels identify one cell. On a DataFrame whose **row index or columns are not unique**, `at` falls back to `loc`. If the frame holds two rows labelled 1007, `df.at[1007, "salary"]` returns a **Series** of both salaries, not a scalar; duplicated column names do the same. Code that assumes `at` always yields a number then fails further on, for example at an `if` test on the result, which raises "The truth value of a Series is ambiguous". Two defences: 1. Check `df.index.is_unique` (and `df.columns.is_unique`) when loading data whose keys should be unique. 2. Prefer `iat` when you already know the position, because a position always names one cell. ## Choosing between them 1. **One cell, known label** — `at`. Clear intent, and the error on a list key catches a whole class of mistakes. 2. **One cell, known position** — `iat`, for example the first value after a sort: `df.sort_values("salary").iat[0, 2]`. 3. **Anything wider** — a row, a column, a range, a list of IDs — `loc` or `iloc`; `at` and `iat` will refuse it. 4. **Many cells in a loop** — stop and vectorise; switching `loc` to `at` inside the loop is a micro-optimisation of the wrong design. ## Series versus DataFrame On a `Series` there is one axis, so `s.at[1007]` and `s.iat[1]` take a single key. The rules are otherwise identical: `at` is label-based, `iat` positional, both return a scalar, and both reject list-like keys. ## Mistakes interviewers listen for - Calling `emp.at[1007]` on a DataFrame and expecting the row; `at` needs a column key too. - Passing a column name to `iat`, which accepts integer positions only. - Promising that `at` always returns a number without mentioning duplicate labels. - Presenting `at` as the fix for a slow row loop, when the fix is a vectorised column operation.

  • What does df.at[1007, 'salary'] return when the row label 1007 appears twice?
    A Series holding both salaries, not a scalar. On a DataFrame whose row or column labels are not unique, `at` falls back to `loc`, which returns every matching row. Code that expects a number then fails later, so check `df.index.is_unique` where keys should be unique, or use `iat` with a known position.
  • Is replacing loc with at inside a for loop over 100,000 rows a good optimisation?
    It makes each lookup cheaper, but the loop still runs Python code per row. The real fix is a vectorised expression over whole columns, which pandas runs as one array operation. Reach for `at` and `iat` when the code genuinely needs a single cell, not to speed up row iteration.

  • df.at accepts a list of labels the way loc does.
  • df.iat takes a row label and a column name.
  • at and iat return a one-cell DataFrame.
  • df.at[1007] returns the whole row like df.loc[1007].
  • df.at always returns a scalar, whatever the labels look like.
  • Swapping loc for at inside a row loop makes the code vectorised.