Sub topic 3
Labels versus positions
This chapter assumes you can build a DataFrame from a dictionary and that you know Python list slicing. It covers the one distinction that decides whether selection code works: pandas can find a row or column by its label (its name in the index or columns) or by its position (its place in line, counting from 0). The next two chapters cover .loc and .iloc in detail. This chapter explains why both exist and how to avoid mixing them up.
Two ways to point at the same cell
Every row has a label and a position. In the example DataFrame below, the row for Lima has the label "b" and the position 1. The column population_k has the label "population_k" and the position 2.
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.index.get_loc("c")) # 2: label to position
print(df.index[2]) # c: position to label
print(df.columns.get_loc("population_k")) # 2: column label to positionIndex.get_loc converts a label into a position. Indexing the index object with a number converts a position into a label. Positions always run from 0 to len - 1. Labels can be any hashable value, such as strings, integers, dates, or tuples.
The two selectors map onto these two ideas:
| Selector | Looks things up by | Slice end | Out-of-range or missing |
|---|---|---|---|
| `.loc` | label | included | `KeyError` for a missing label |
| `.iloc` | position | excluded | `IndexError` for a single bad position |
The slice rule follows from the lookup type. A position slice behaves like a Python list slice, so 1:3 stops before position 3. A label slice has no "next label" to stop before, because labels need not be sorted or numeric. So "b":"d" includes "d".
print(df.loc["b":"d"]) # rows b, c, d (three rows)
print(df.iloc[1:3]) # rows b, c (two rows)The decision in one picture
The integer index trap
With a string index like "a" to "e", labels and positions never look alike. Trouble starts when the index is made of integers. The default index, a RangeIndex, counts from 0, so labels and positions match until you filter, sort, or drop rows.
nums = df.reset_index(drop=True) # index is now 0, 1, 2, 3, 4
big = nums[nums["population_k"] > 3000] # keeps Lima, Pune, Cairo
print(big.index.tolist()) # [1, 2, 3]
print(big.loc[1]) # label 1: the Lima row
print(big.iloc[1]) # position 1: the Pune row
print(big.loc[1:2]) # labels 1 and 2: Lima and Pune
print(big.iloc[1:2]) # position 1 only: PuneAfter filtering, the labels are [1, 2, 3], but the positions are still 0, 1, 2. The expression big.loc[1] and the expression big.iloc[1] return different rows. Neither is wrong, but only one matches what you meant.
Two related failures are common:
try:
big.loc[0]
except KeyError as err:
print("KeyError:", err) # label 0 was filtered out
print(big.iloc[0]["city"]) # Lima: position 0 always existsIf you wrote big.loc[0] meaning "the first row", you get a KeyError. This is a useful failure, because it tells you immediately. The harder case is when the label does exist but points at a different row than you intended, as with big.loc[1] above. That returns data silently.
Negative numbers and bad bounds
Negative numbers mean different things in the two systems.
.iloc[-1]is the last row, as in a Python list..loc[-1]looks for a row whose label is-1. On a string index this raisesKeyError. On an integer index it works only if a row has that label.
print(df.iloc[-1]["city"]) # Quito, the last row
try:
df.loc[-1]
except KeyError as err:
print("KeyError:", err)Out-of-range behavior also differs by selection type:
- A single position outside the data, such as
df.iloc[10], raisesIndexError. - A position slice outside the data, such as
df.iloc[3:100], is clipped without an error, like a Python list slice. It returns the last two rows here. - A single missing label raises
KeyError. - A label slice whose endpoint is missing works only if the index is sorted (monotonic). On an unsorted index, a missing endpoint raises
KeyError.
print(df.iloc[3:100]) # rows d and e, no errorDuplicate labels
Labels are not required to be unique. If two rows share a label, .loc with that label returns all of them as a DataFrame, while a unique label returns a Series. Positions are always unique, so .iloc[n] always returns exactly one row.
dup = pd.DataFrame({"v": [10, 20, 30]}, index=["x", "x", "y"])
print(dup.loc["x"]) # a DataFrame with two rows
print(dup.loc["y"]) # a Series with one value per column
print(dup.iloc[0]) # always one rowCode that expects one row from .loc can break when data changes and a label becomes duplicated. If you need a guarantee, check df.index.is_unique first, or select by position.
Mixing labels and positions
Sometimes you hold one kind of reference for rows and the other for columns. For example, you may know the row by position but the column by name. Do not guess. Convert one side so the whole call uses one system.
# Rows by position, column by name: turn row positions into labels
labels = df.index[1:3]
print(df.loc[labels, "city"])
# Rows by label, columns by position: turn column labels into positions
cols = [df.columns.get_loc("city"), df.columns.get_loc("population_k")]
print(df.iloc[df.index.get_loc("c"), cols])The first call selects city for rows b and c. The second selects the city and population_k values for row c. Converting costs a line of code, but it makes the intent explicit and survives column reordering better than hard-coded column numbers.
Plain brackets are a hybrid
The bare df[...] syntax guesses what you mean, and that guess depends on what you pass.
- A single column name or a list of names selects columns by label.
- A slice of integers, such as
df[1:3], selects rows by position. - A slice of labels, such as
df["b":"d"], selects rows by label, with the end included. - A boolean Series selects rows (covered in a later chapter).
print(df[1:3]) # rows b and c, by position
print(df["b":"d"]) # rows b, c, d, by labelThis works, but the same brackets mean different things depending on the argument, and an integer index makes it worse. Prefer .loc and .iloc for row selection so the code states which system it uses.
Common errors and how to avoid them
- Assuming
0is always the first label. After filtering or sorting, label0may not exist. Use.iloc[0]for "the first row". - Forgetting that
.locslices include the end. If a label slice returns one more row than expected, this is the cause. Use.ilocwith a position slice if you want an exclusive end. - Using
.locwith positions on a string index.df.loc[1]raisesKeyErrorhere, because no row is labeled1. - Reading
ilocnumbers as labels.iloc[1:3]means positions 1 and 2, whatever the labels are. - Relying on column positions. Column order can change when someone edits the code that builds the DataFrame. Select columns by name unless position is the point.
- Ignoring duplicate labels. Check
index.is_uniquewhen a lookup must return one row.
Exercise
Given nums = df.reset_index(drop=True) and big = nums[nums["population_k"] > 3000], what do big.loc[1:2] and big.iloc[1:2] return, and why do they differ?
Show answer
big.loc[1:2] returns the Lima and Pune rows, because the labels are 1, 2, 3 and a label slice includes both ends. big.iloc[1:2] returns only the Pune row, because it takes position 1 and excludes position 2, as a Python slice does.
Exercise
You want the city value of the last row of any DataFrame, whatever its index looks like. Which expression is safe, and why does df.loc[-1, "city"] fail on the example DataFrame?
Show answer
Use df.iloc[-1]["city"], or df["city"].iloc[-1]. Position -1 always means the last row. df.loc[-1, "city"] looks for a row labeled -1, and the example index contains only "a" to "e", so it raises KeyError.