Sub topic 4
Selecting Rows and Columns with .loc
.loc is the label-based selector in pandas. It takes a row selector and an optional column selector in one pair of square brackets. This chapter covers what .loc accepts, what shape of result you get back, how its slices behave, and the errors you are most likely to hit.
This chapter assumes you can write basic Python, including lists, dictionaries, and slices. It also assumes you have pandas installed and imported as pd, and that you can build a DataFrame from a dictionary. It builds on the earlier chapters on index, columns, and values, bracket column selection, and the difference between labels and positions.
The shape of a .loc call
The general form is df.loc[row_selector, column_selector]. If you leave out the column selector, you get all columns. To keep all rows and choose columns, write : for the row selector.
Every example below uses this DataFrame. Its row labels are the strings "a" to "e".
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"]) # one row, returned as a Series
print(df.loc[["b", "d"]]) # a list of labels, returned as a DataFrame
print(df.loc["b", "city"]) # one row and one column, a single value
print(df.loc[["b", "d"], "city"]) # several rows, one column: a Series
print(df.loc[:, ["city", "continent"]]) # all rows, two columns: a DataFrameEach selector can be a single label, a list of labels, a slice, a boolean mask, or a function. The table summarizes what each form does.
| Selector | Example | Meaning |
|---|---|---|
| Single label | `df.loc["b"]` | One row or one column. The dimension is dropped. |
| List of labels | `df.loc[["b", "d"]]` | Those rows, in the order you list them. |
| Slice | `df.loc["b":"d"]` | A label range, including both endpoints. |
| Boolean mask | `df.loc[df["population_k"] > 3000]` | Rows where the mask is `True`. |
| Callable | `df.loc[lambda d: d["population_k"] > 3000]` | The function receives the DataFrame and returns any of the above. |
What shape you get back
The result's type depends on whether each selector is a single label or a collection.
- A single label for the rows and a single label for the columns returns one scalar value.
- A single label on one axis and a list or slice on the other returns a Series.
- A list, slice, or mask on both axes returns a DataFrame.
A one-item list keeps the dimension. df.loc[["b"]] is a DataFrame with one row, while df.loc["b"] is a Series. This matters when later code expects a particular type, so choose the form on purpose.
Slices include both endpoints
Ordinary Python slices stop before the end value. A .loc slice does not, because labels have no natural "one past" value. Both endpoints are included.
print(df.loc["b":"d"]) # rows b, c, d
print(df.loc["b":"d", "city":"population_k"]) # also slices columns by label
print(df.loc[:"c"]) # from the start through c
print(df.loc["c":]) # from c to the endThe second line shows that a column slice works the same way. It selects city, country, and population_k, because population_k is included. Slices follow the order of the labels as stored, not alphabetical order.
Integer labels follow the same rule. This is a common source of confusion because the numbers look like positions.
t = pd.DataFrame({"v": [1, 2, 3]}, index=[10, 20, 30])
print(t.loc[10:20]) # labels 10 and 20, two rows
print(t.iloc[0:2]) # positions 0 and 1, the same two rowst.loc[0:2] would not give the first two rows. It asks for labels between 0 and 2, and none of the labels fall in that range.
Filtering rows with a mask
A boolean mask is a Series of True and False values, one per row. Passing it to .loc keeps the True rows. The advantage over df[mask] is that you can name the columns in the same call.
big = df["population_k"] > 3000
south_america = df["continent"] == "South America"
print(df.loc[big, ["city", "population_k"]])
print(df.loc[big & south_america, "city"])
print(df.loc[~big, "city"])The first call returns Lima, Pune, and Cairo with two columns. The second returns only Lima, as a Series, because only one row passes both tests. Build each comparison as its own variable, or put each one in parentheses. The operators &, |, and ~ bind more tightly than comparison operators, so df["a"] > 1 & df["b"] < 2 does not do what it appears to do.
A mask given as a Series is aligned to the DataFrame by index label. If the mask's index does not match the DataFrame's, pandas raises an IndexingError about an unalignable boolean Series. A mask given as a plain list or NumPy array is matched by position, so its length must equal the number of rows.
Callables
A function passed to .loc is called with the DataFrame and must return a valid selector. This is useful in method chains, where an intermediate result has no variable name.
result = (
df.assign(population_m=df["population_k"] / 1000)
.loc[lambda d: d["population_m"] > 3, ["city", "population_m"]]
)
print(result)Without the callable, you would need a temporary variable to refer to the DataFrame that assign produced.
Assigning with .loc
The same selectors work on the left side of an assignment. One .loc call both finds the cells and writes to them.
work = df.copy()
work.loc[work["population_k"] > 3000, "size"] = "large"
work.loc["a", "population_k"] = 710
print(work[["city", "population_k", "size"]])Assigning to a column name that does not exist creates it. Rows that were not selected get NaN in the new column. The copy on the first line keeps df unchanged for later examples. A later chapter covers copies and chained indexing in detail.
Common errors
Most .loc errors fall into a few groups.
KeyErrorfrom a missing label.df.loc["z"]raisesKeyError. A list that contains a missing label, such asdf.loc[["a", "z"]], also raisesKeyError. Current pandas no longer fills missing labels withNaN. If you want that behavior, usedf.reindex(["a", "z"]).- Slicing with a missing endpoint. A slice endpoint that is not in the index works only if the index is sorted. On an unsorted index, pandas cannot tell which rows lie between the labels and raises
KeyError. Calldf.sort_index()first if you slice by labels that may be absent. - Using positions by mistake.
df.loc[0]on a string index raisesKeyError, because there is no label0. Use.ilocwhen you mean a position. - Duplicate labels. If the index has repeated labels,
df.loc["x"]returns every matching row as a DataFrame, not a Series. Code that expects a single row can break when duplicates appear in the data. - Wrong mask length. A list-like mask with a different length than the row count raises an error. A mask built from a different DataFrame may fail to align.
Choosing between .loc and bracket selection
Use df["col"] or df[["a", "b"]] for plain column selection, since it is short and clear. Use .loc when you need to select rows and columns together, slice by label, or assign. Using .loc for filtering plus a column list also communicates intent: the reader sees which rows and which columns you want in one expression.
Exercise
Using the DataFrame df from this chapter, write one .loc call that returns the city and country columns for rows whose continent is "South America" and whose population_k is above 3000. What type does it return, and which row does it contain?
Show answer
df.loc[(df["continent"] == "South America") & (df["population_k"] > 3000), ["city", "country"]]. The column selector is a list, so the result is a DataFrame. It contains one row, label b, with Lima and Peru. Quito is in South America but has 2800 thousand people, so it fails the second test.
Exercise
Given t = pd.DataFrame({"v": [1, 2, 3, 4]}, index=[10, 20, 30, 40]), what does t.loc[20:30] return, and what does t.iloc[20:30] return?
Show answer
t.loc[20:30] returns two rows, labels 20 and 30, because the slice works on labels and includes both endpoints. t.iloc[20:30] returns an empty DataFrame, because it works on positions and the table has only positions 0 to 3.