Label-based selection
Retrieve specific records or fields by their index and column labels.
Pandas · Const
DataFrame.loc selects and assigns DataFrame rows and columns by label, with optional boolean-array filtering. Label slices include both endpoints, and numeric keys remain labels rather than positions.
DataFrame.loc is a label-oriented indexer for selecting or assigning rows and columns. It accepts individual labels, label collections, inclusive label slices, boolean masks, callable indexers, and alignable objects.
df.loc[row_indexer, column_indexer]| Name | Type | Description |
|---|---|---|
indexer | label, list-like, slice, boolean array, alignable Series/Index, or callable | Row and column indexers supplied inside df.loc[row_indexer, column_indexer]. Supported forms include labels, lists or arrays of labels, inclusive label slices, boolean arrays, alignable boolean Series, alignable Index objects, and callables. |
A cross-section consisting of selected row(s) or column(s) from the DataFrame; the exact result type depends on the indexers.
import pandas as pd
df = pd.DataFrame(
{"name": ["Ada", "Linus", "Grace"], "score": [95, 82, 91]},
index=["a", "b", "c"],
)
selected = df.loc[["a", "c"], ["name", "score"]]
high_scores = df.loc[df["score"] >= 90, "name"]
df.loc["b", "score"] = 88
print(selected)
print(high_scores)Uses label lists, a boolean condition, and a label pair to select and update DataFrame values.
Retrieve specific records or fields by their index and column labels.
Keep rows satisfying a condition and optionally select particular columns.
Change selected cells or ranges without relying on positional offsets.
Select an inclusive range of ordered index or column labels.
DataFrame.ilocDataFrame.atDataFrame.iatSeries.loc