.loc[] (Pandas)

.loc[] selects rows and columns from a DataFrame by their labels (index and column names). It is label-based indexing, and unlike Python slicing it includes the end label of a range.

Pandas

The general form is df.loc[row_selector, column_selector]. Each selector can be a single label, a list of labels, a label slice, or a boolean mask. Because it works on labels, df.loc['a':'c'] returns rows a, b, and c — the stop label is inclusive, which trips up people used to integer slicing.

.loc is also the correct, warning-free way to assign to a subset: df.loc[df.age > 30, 'status'] = 'senior' sets a value on exactly the rows that match a condition, avoiding the chained-assignment SettingWithCopyWarning.

Use .loc when your rows have meaningful labels (dates, IDs, names). Reach for its sibling .iloc when you only care about integer position.

Syntax

df.loc[row_labels, column_labels]

Examples

Python

import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]}, index=["x", "y", "z"])
print(df.loc["y", "a"])

Output:

2

Learn it in a lesson

See also

Back to the Dictionary