Sub topic 6
Selecting data with [], loc, and iloc
This chapter assumes you can create a Series and a DataFrame, and that you know what an Index is. You should also be comfortable with Python list slicing. By the end you will know which accessor to use for a given selection, what type each one returns, and which mistakes cause KeyError or silently wrong rows.
Three tools, three questions
pandas gives you three ways to pick data. They differ in what they ask you to supply.
| Accessor | You supply | Slice end | Typical use |
|---|---|---|---|
| `[]` | A column name, a list of column names, a boolean mask, or a row slice | Depends on slice type | Quick column access and filtering |
| `loc` | Index labels and column labels | Inclusive | Selection by name, and assignment |
| `iloc` | Integer positions | Exclusive | Selection by position |
The examples below use one DataFrame with city names as the Index. Using labels that are not integers makes it obvious whether a label or a position is being used.
import pandas as pd
df = pd.DataFrame(
{
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
},
index=["Oslo", "Lima", "Pune", "Rome"],
)
print(df)Square brackets
The meaning of [] depends on what you put inside it.
import pandas as pd
df = pd.DataFrame(
{"pop_m": [0.7, 10.7, 3.1, 2.8], "region": ["EU", "SA", "AS", "EU"]},
index=["Oslo", "Lima", "Pune", "Rome"],
)
print(df["pop_m"]) # a Series
print(type(df[["pop_m"]]).__name__) # DataFrame
print(df[1:3]) # rows Lima and Pune, by position
print(df["Lima":"Pune"]) # rows Lima and Pune, by label
print(df[df["pop_m"] > 3]) # rows where the mask is True- A single column name returns a Series.
- A list of column names returns a DataFrame, even if the list has one item.
- A slice selects rows. An integer slice such as
1:3is positional and excludes the end. A label slice such as"Lima":"Pune"is label-based and includes the end. - A boolean Series of the same length selects the rows where it is
True.
df["Lima"] raises KeyError, because a bare label inside [] is looked up as a column name. Row selection by a single label needs loc.
Because [] mixes several behaviors, many people use it only for columns and masks, and use loc and iloc for everything else.
Selection by label with loc
loc takes df.loc[rows, columns]. Either part can be a single label, a list of labels, a slice, or a boolean mask. Omit the second part to keep all columns.
import pandas as pd
df = pd.DataFrame(
{"pop_m": [0.7, 10.7, 3.1, 2.8], "region": ["EU", "SA", "AS", "EU"]},
index=["Oslo", "Lima", "Pune", "Rome"],
)
print(df.loc["Lima"]) # Series: one row, indexed by column names
print(df.loc["Lima", "pop_m"]) # 10.7, a single value
print(df.loc["Oslo":"Pune", "pop_m"]) # Oslo, Lima, Pune: end label included
print(df.loc[["Rome", "Oslo"], :]) # rows in the order you listed themTwo rules explain most of the return types:
- A single label in one position removes that dimension.
df.loc["Lima"]is a Series, anddf.loc["Lima", "pop_m"]is a scalar. - A list or a slice keeps the dimension.
df.loc[["Lima"]]is a one-row DataFrame.
Label slices include the end label because pandas cannot know what "the next label" would be. Positional slices follow Python and exclude the end.
Selection by position with iloc
iloc ignores the Index and counts from zero.
import pandas as pd
df = pd.DataFrame(
{"pop_m": [0.7, 10.7, 3.1, 2.8], "region": ["EU", "SA", "AS", "EU"]},
index=["Oslo", "Lima", "Pune", "Rome"],
)
print(df.iloc[0]) # first row as a Series
print(df.iloc[0:2, 0]) # Oslo and Lima, first column only
print(df.iloc[[0, 3], [1]]) # Oslo and Rome, region column, as a DataFrame
print(df.iloc[-1]) # last rowiloc accepts integers, lists of integers, slices, and boolean arrays. It does not accept a boolean Series with an Index, because that would imply label alignment. Convert the mask first with .to_numpy().
Why integer indexes cause trouble
When the Index holds integers, a plain integer can mean a label or a position. The two accessors resolve this by being explicit.
import pandas as pd
s = pd.Series(["a", "b", "c"], index=[2, 1, 0])
print(s.loc[0]) # c, the row labeled 0
print(s.iloc[0]) # a, the first rowThe same ambiguity affects s[0]. On an integer Index, [] treats the number as a label. On a string Index, older pandas versions fell back to position, and current versions warn about it. Do not rely on either behavior. Use loc or iloc whenever the intent matters.
A common source of this bug is filtering or sorting a DataFrame and then using df.iloc[0] or df.loc[0] as if they were interchangeable. After filtering, the first row is no longer labeled 0.
import pandas as pd
df = pd.DataFrame({"x": [5, 6, 7, 8]})
sub = df[df["x"] > 6] # keeps labels 2 and 3
print(sub.iloc[0]["x"]) # 7, the first remaining row
print(sub.loc[2, "x"]) # 7, the row labeled 2
# sub.loc[0] would raise KeyError: label 0 was filtered outCombining a mask and a column list
The most useful loc form puts a boolean mask on the rows and a list of labels on the columns.
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"],
})
big = df.loc[df["pop_m"] > 3, ["city", "pop_m"]]
print(big) # rows for Lima and PuneThe mask is evaluated first and produces a Series of True and False values. loc then keeps the rows marked True and the two named columns. Doing this in one call is clearer than df[mask][cols], and it is the only form that is safe for assignment.
Assigning through loc
loc and iloc can appear on the left side of =.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
df.loc[df["pop_m"] > 3, "size"] = "big"
df.loc[df["city"] == "Oslo", "pop_m"] = 0.75
print(df)The first line creates a new column size. Rows that did not match the mask receive NaN. The second line updates one cell in place. A single loc call with rows and columns writes to the original DataFrame. The chained form df[mask]["size"] = "big" runs two separate operations, and the write may go to a temporary copy. Chapter 13 covers this in detail.
Fast scalar access with at and iat
For reading or writing one value, at (label) and iat (position) skip the overhead of the general machinery.
import pandas as pd
df = pd.DataFrame({"pop_m": [0.7, 10.7]}, index=["Oslo", "Lima"])
print(df.at["Lima", "pop_m"]) # 10.7
print(df.iat[0, 0]) # 0.7Use them inside loops that touch single cells. For everything else, loc and iloc are enough.
Common errors
KeyErrorfromdf["Lima"]: a row label was used in[]. Usedf.loc["Lima"].KeyErrorfromloc: the label does not exist, often because filtering removed it. Checkdf.index.IndexErrorfromiloc: a position is outside the data, such asdf.iloc[10]on four rows. Slices are the exception and never raise for out-of-range bounds.- Wrong rows with a label slice:
loc[a:b]includesb, so the result has one more row than the sameilocslice. - A Series where you expected a DataFrame: pass a list, as in
df[["pop_m"]].
Exercise
Given df with Index ["Oslo", "Lima", "Pune", "Rome"] and columns pop_m and region as above, write one expression that returns a DataFrame with the region column for Lima and Pune only, using labels. Then write the equivalent expression using positions.
Show answer
By label: df.loc[["Lima", "Pune"], ["region"]] or df.loc["Lima":"Pune", ["region"]]. By position: df.iloc[1:3, [1]]. Using a list for the column keeps the result a DataFrame. The label slice includes "Pune", while the position slice 1:3 excludes position 3, so both return the same two rows.
Exercise
A DataFrame has the default Index 0, 1, 2, 3. You run sub = df[df["x"] > 6] and the rows with labels 2 and 3 remain. What do sub.loc[0] and sub.iloc[0] do?
Show answer
sub.loc[0] raises KeyError, because label 0 was removed by the filter. sub.iloc[0] returns the first remaining row, which is the row labeled 2.