Sub topic 4
Selecting Rows and Columns with .loc
This chapter assumes you can build a DataFrame from a dictionary and know that a DataFrame has an index (row labels), columns, and values. It also assumes you know that pandas can select by label or by position. Here we cover label-based selection with .loc.
The working model
.loc takes two parts in square brackets: df.loc[row_selector, column_selector]. Both parts work on labels, never on positions. If you leave out the column part, you get all columns.
The examples below use this DataFrame.
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"],
)What each selector returns
The type of selector you pass decides the shape of the result.
| Selector | Example | Result |
|---|---|---|
| One label for both parts | `df.loc["b", "city"]` | A single value |
| One label for one part | `df.loc["b"]` | A Series |
| List of labels | `df.loc[["b", "d"]]` | A DataFrame |
| Slice | `df.loc["b":"d"]` | A DataFrame |
| Boolean mask | `df.loc[df["population_k"] > 3000]` | A DataFrame |
Passing a list, even a list of one label, keeps the result two-dimensional. df.loc["b"] returns a Series, but df.loc[["b"]] returns a one-row DataFrame.
Selecting rows and columns together
print(df.loc["b":"d", ["city", "population_k"]])
print(df.loc[:, "city":"population_k"])The first call returns rows b, c, and d. The second keeps every row and returns the columns city, country, and population_k. Label slices include both endpoints. This differs from Python list slices and from .iloc, which excludes the end.
Masks inside .loc
A boolean mask is a Series of True and False values with the same index as the DataFrame. .loc keeps the rows where the mask is True. The column part then picks which columns to return.
big = df["population_k"] > 3000
print(df.loc[big, ["city", "country"]])This returns Lima and Cairo, with only the city and country columns. Selecting rows and columns in one call is clearer than filtering first and picking columns afterward.
Common errors
- KeyError on a missing label.
df.loc["z"]fails, and so does a list that contains a missing label such asdf.loc[["a", "z"]]. Check labels withdf.index. - Expecting positions.
df.loc[1]looks for a label equal to1. Our index holds strings, so this raises aKeyError. Use.iloc[1]for the second row. - Forgetting the inclusive end.
df.loc["b":"d"]has three rows, not two. - Slicing an unsorted index. Slicing with labels that are missing from an unsorted index raises an error. Slices on a sorted index tolerate missing endpoints.
- Mask with a different index. A mask built from another DataFrame can fail or misalign, because
.locmatches mask labels to index labels.
Assigning with .loc
Because .loc names rows and columns in one step, it can also write values.
df.loc[df["continent"] == "Asia", "population_k"] = 3200
print(df.loc["c"])This sets population_k to 3200 for every Asian row, which here is only Pune. The write goes to df itself.
Exercise
Using the df above, write one .loc call that returns the city and country columns for every row whose continent is "South America". Which rows come back?
Show answer
df.loc[df["continent"] == "South America", ["city", "country"]] returns rows b (Lima, Peru) and e (Quito, Ecuador). The mask picks the rows and the list picks the columns.