Sub topic 6
Selecting data with [], loc, and iloc
This chapter assumes you can build a Series and a DataFrame and know that every row carries an Index label. Here you learn the three ways to pull data out of them, and when each one is safe to use.
Three tools, three jobs
| Tool | Selects by | Slice end | Typical use |
|---|---|---|---|
| `df[...]` | column name, or a row slice or mask | depends on the argument | quick column access |
| `df.loc[rows, cols]` | labels and boolean masks | inclusive | most selection |
| `df.iloc[rows, cols]` | integer positions | exclusive | "the first 5 rows" |
Plain brackets
The meaning of [] depends on what you put inside it.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
print(type(df["city"])) # Series: a single name
print(type(df[["city", "pop_m"]])) # DataFrame: a list of names
print(df[1:3]) # rows at positions 1 and 2Brackets are convenient, but the mixed behavior is why loc and iloc exist. Use them when you want to be explicit.
Label-based selection with loc
loc takes a row selector and an optional column selector. Both refer to labels. Setting city as the Index makes this easy to see.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
by_city = df.set_index("city")
print(by_city.loc["Lima", "pop_m"]) # 10.7, a single value
print(by_city.loc["Oslo":"Pune"]) # Oslo, Lima, Pune: end label included
print(by_city.loc[["Rome", "Oslo"], "region"]) # rows in the order you ask forA label slice includes its end point because labels have no natural "one past the end." A label that does not exist raises KeyError.
Position-based selection with iloc
iloc ignores labels and counts from 0, like a Python list.
print(by_city.iloc[0, 1]) # first row, second column: "EU"
print(by_city.iloc[0:2]) # Oslo and Lima: end position excluded
print(by_city.iloc[-1]) # last row, returned as a SeriesUse iloc when position is what matters. Use loc when the label is what matters. Positions can shift after sorting or filtering, but labels stay attached to their rows.
Masks inside loc
A boolean mask picks rows, and a list of labels picks columns, in one call.
big = df.loc[df["pop_m"] > 3, ["city", "pop_m"]]
print(big) # Lima and Pune, keeping their original labels 1 and 2Doing the row and column choice in one loc call matters later, when you assign into a selection.
Common errors
- Integer labels. If the Index is
[10, 20, 30], thens[0]fails ands.loc[0]fails. Onlys.iloc[0]works. If the Index is[2, 1, 0], thens.loc[0]ands.iloc[0]return different rows. Never rely ons[0]. - Mixing up slice ends.
loc[0:2]returns three rows on a default Index.iloc[0:2]returns two. - Single versus list.
df.loc[:, "pop_m"]returns a Series.df.loc[:, ["pop_m"]]returns a one-column DataFrame. - Mask shape. The mask must have the same length and labels as the rows. A mask built from a different DataFrame is aligned by label, which can raise an error or select the wrong rows.
Exercise
A DataFrame has the Index [3, 2, 1, 0]. What is the difference between df.loc[0] and df.iloc[0]?
Show answer
df.loc[0] returns the row whose label is 0, which is the last row. df.iloc[0] returns the row at position 0, which is the first row, labeled 3.
Exercise
Write one loc call on df (the DataFrame above, with a default Index) that returns the city and region of rows where pop_m is below 3.
Show answer
df.loc[df["pop_m"] < 3, ["city", "region"]] returns Oslo and Rome with their city and region columns.