Sub topic 14
Fast scalar access with .at and .iat
This chapter covers the two accessors that read or write exactly one cell, .at and .iat. It assumes you have read the earlier chapters on .loc, .iloc, and set_index. You should know that .loc works on labels and .iloc works on positions.
What a scalar accessor is for
A scalar is a single value, such as one number or one string. .loc and .iloc can return a scalar, but they also handle slices, lists, and boolean masks. They have to inspect the key you pass to work out which case applies, and that costs time on every call.
.at and .iat skip that work. They accept exactly one row key and one column key and return one cell. The pairing mirrors the two earlier selectors:
| Accessor | Key type | Equivalent general selector |
|---|---|---|
| `.at` | row label, column label | `.loc` |
| `.iat` | row position, column position | `.iloc` |
Reading a single value
The examples reuse the city DataFrame, with city moved into the index so that a city name is a row label.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)
by_city = df.set_index("city")
print(by_city.columns.tolist())
print(by_city.loc["Lima", "population_k"])
print(by_city.at["Lima", "population_k"])
print(by_city.iat[1, 1])All three lookups print 10092. After set_index, the remaining columns are country, population_k, and continent. Position 1 on the column axis is therefore population_k, and position 1 on the row axis is Lima.
Note that .iat counts from zero and ignores the index labels. If someone reorders the rows or columns later, the same .iat call returns a different cell. Use .at when you know the name of the cell and .iat when you know its place.
Writing a single value
Both accessors work on the left side of an assignment.
by_city.at["Oslo", "population_k"] = 710
by_city.iat[0, 1] = 711
print(by_city.loc["Oslo", "population_k"])The second assignment overwrites the first, so the output is 711. Each call changes one cell in place on by_city. This is not chained indexing. The accessor receives both keys together, so pandas knows which object to write into.
Keep the new value compatible with the column's dtype. Writing the string "n/a" into an integer column forces pandas to convert the whole column to object in older versions. Newer versions warn about it, and pandas 3 raises an error instead.
What `.at` and `.iat` refuse to do
The restrictions are the price of the speed. Each accessor raises an error when you ask for more than a single cell.
try:
by_city.at["Rome", "population_k"]
except KeyError as err:
print("KeyError:", err)
try:
by_city.iat[10, 0]
except IndexError as err:
print("IndexError:", err)A missing label raises KeyError, and a position outside the frame raises IndexError. Neither accessor tries to be forgiving.
| What you pass | `.loc` / `.iloc` | `.at` / `.iat` |
|---|---|---|
| One label or position per axis | Returns a scalar | Returns a scalar |
| A slice such as `"b":"d"` | Returns a block | Raises an error |
| A list of keys | Returns a block | Raises an error |
| A boolean mask | Returns the matching rows | Raises an error |
| Only one key | Returns a row | Raises an error |
Duplicate index labels are a special case. If the row label appears twice, .at cannot return a single cell. Depending on the version and the data, it can return several values instead of one. If your index might contain duplicates, check by_city.index.is_unique first, or use a selector that expects multiple results.
Choosing an accessor
The diagram shows how to pick among the four selectors when you only need cell values.
Mixing labels and positions
Sometimes you have a row label but only a column position, or the reverse. .at and .iat do not allow a mixed pair. You can convert one kind of key into the other with get_loc.
row = by_city.index.get_loc("Pune")
col = by_city.columns.get_loc("population_k")
print(by_city.iat[row, col])get_loc returns the integer position of a label. It returns a plain integer only when the labels are unique, so this pattern has the same duplicate-label caveat as .at.
Measuring the difference
The gap between .loc and .at is small for one lookup and visible only when you repeat the lookup many times. The timing below measures it on your machine. The numbers depend on your hardware and pandas version, so run it rather than trusting a figure from a book.
import timeit
n = 10_000
t_loc = timeit.timeit(lambda: by_city.loc["Lima", "population_k"], number=n)
t_at = timeit.timeit(lambda: by_city.at["Lima", "population_k"], number=n)
print(f"loc: {t_loc:.3f}s for {n} calls")
print(f"at: {t_at:.3f}s for {n} calls")Expect .at to be faster. The advantage matters only inside a loop that touches cells one by one. In ordinary code, readability matters more than the saving.
A loop that uses `.at`, and a better way
Suppose you need to label each city as large or small. A row-by-row loop with .at is correct:
by_city["size"] = "small"
for city in by_city.index:
if by_city.at[city, "population_k"] > 3000:
by_city.at[city, "size"] = "large"
print(by_city[["population_k", "size"]])Lima, Pune, and Cairo end up as large. The same result takes one line with a boolean mask and .loc:
by_city["size"] = "small"
by_city.loc[by_city["population_k"] > 3000, "size"] = "large"The mask version works on the whole column at once, so it is shorter and much faster on large frames. Prefer it whenever the rule can be written as a condition.
Common mistakes
- Passing a slice or list.
by_city.at["Lima", ["country", "population_k"]]fails. Use.locwhen you want more than one cell. - Using
.iatafter the order changes. Sorting or dropping rows changes positions, so a hard-coded.iat[0, 1]can point at a different cell. Use.atwith labels when the data may be reordered. - Using a label with
.iat..iatexpects integers.by_city.iat["Lima", 1]raises an error. - Assuming a missing label is created. On a read, a missing label raises
KeyError. Check with"Rome" in by_city.indexif you are not sure. - Writing a mismatched type. Assigning a value that does not fit the column's dtype can upcast the column or raise an error, depending on the pandas version.
Summary of the decision
Use .at when you know a row label and a column label and need one cell. Use .iat when you know the positions. Use .loc or .iloc for everything else. All four accept the same kinds of keys for single cells, so you can switch between them without changing the result, only the speed and the strictness.
Exercise
Given by_city from this chapter, write one line that sets the population of Quito to 2850 using a label-based scalar accessor, and one line that reads the same cell using a position-based scalar accessor. Quito is the last row, and population_k is the second column.
Show answer
Set it with by_city.at["Quito", "population_k"] = 2850. Read it with by_city.iat[4, 1]. Position 4 is the fifth row, Quito, and position 1 is population_k because city is now the index and not a column.
Exercise
A colleague writes by_city.at["Lima":"Cairo", "population_k"] to get three populations. What happens, and which accessor should replace .at?
Show answer
It raises an error, because .at accepts only a single label per axis and never a slice. Replace it with .loc, as in by_city.loc["Lima":"Cairo", "population_k"]. Because .loc slices include both endpoints, this returns the rows from Lima through Cairo.
Exercise
You need the population of the city called "Pune", but the only column information you have is the column name, and the row information is the row's label. Explain why by_city.iat["Pune", "population_k"] fails and give a working alternative that still uses .iat.
Show answer
.iat accepts only integer positions, so strings raise an error. Convert the labels to positions with get_loc: by_city.iat[by_city.index.get_loc("Pune"), by_city.columns.get_loc("population_k")]. The simpler option is by_city.at["Pune", "population_k"], since both keys are labels.