Sub topic 3
Labels versus positions
This chapter assumes you can create a DataFrame from a dictionary and read basic Python slices. It uses the five-city DataFrame from the earlier chapters, with the string index a to e.
Two ways to name a row
Every row has two identities. Its label is the value stored in the index. Its position is the integer count from the start, beginning at 0. Columns work the same way. A column has a name and a position.
In the example DataFrame, the row for Lima has the label "b" and the position 1. The population_k column has the name "population_k" and the position 2.
pandas gives each identity its own selector:
.locselects by label..ilocselects by integer position.
Keeping the two apart prevents most indexing bugs. When you write a selection, decide first which identity you are using.
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"],
)
print(df.loc["b", "city"]) # label "b", column name "city"
print(df.iloc[1, 0]) # position 1, column position 0Both lines print Lima. They reach the same cell by different routes.
The slice rule that differs
The two selectors treat slice endpoints differently. This is the most common source of off-by-one errors.
| Selector | Identifies by | Slice end |
|---|---|---|
| `.loc` | Label | Included |
| `.iloc` | Position | Excluded |
.iloc follows normal Python slicing, so 1:3 means positions 1 and 2. .loc includes the end label because labels have no natural "next" value. For a string index, there is no way to say "up to but not including" a label.
# .loc uses labels and includes both slice endpoints
print(df.loc["b":"d", ["city", "population_k"]])
# .iloc uses positions and excludes the slice end
print(df.iloc[1:3, [0, 2]])The first call returns three rows: b, c, and d. The second returns two rows: b and c. Both return the city and population_k columns. In .iloc, those columns are given as positions 0 and 2.
When labels look like positions
The distinction matters most when the index holds integers. A default index is 0, 1, 2, ..., so labels and positions match until you filter or sort the rows.
small = df.loc[["c", "d", "e"]].reset_index(drop=True)
print(small.loc[0, "city"])
kept = df[df["population_k"] > 3000]
kept.index = [10, 11]
print(kept.loc[10, "city"])
print(kept.iloc[0, 0])After the filter, kept has the labels 10 and 11, but its positions are still 0 and 1. kept.loc[10, "city"] and kept.iloc[0, 0] return the same city. kept.loc[0, "city"] would raise a KeyError, because no row has the label 0.
A common error is writing df.loc[0] on a DataFrame whose index is strings. That raises a KeyError, since 0 is not a label. The reverse, giving .iloc a label such as df.iloc["b"], raises a TypeError. When you get one of these errors, check which selector you used and what the index contains.
Choosing a selector
Use this checklist:
- If you know the row's value in the index, use
.loc. - If you want "the first three rows" or "the last row", use
.iloc. - If the rows come from a condition, use
.locwith a boolean mask. - If you must write code that survives re-sorting or filtering, prefer labels.
Position-based code is fragile. If the data is sorted differently, .iloc[0] returns a different row, while .loc["a"] still returns the same one.
Exercise
Using the five-city DataFrame, what does df.loc["c":"e", "country"] return, and which .iloc call returns the same values?
Show answer
It returns the country values for rows c, d, and e: India, Egypt, and Ecuador. The same values come from df.iloc[2:5, 1]. The .loc end label e is included, so the .iloc end must be 5, one past position 4. Column country is at position 1.
Exercise
A DataFrame has the index [10, 20, 30]. What happens when you run df.loc[0], and what should you run to get the first row?
Show answer
df.loc[0] raises a KeyError, because no row has the label 0. To get the first row by position, run df.iloc[0]. To get it by label, run df.loc[10].