Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Pandas · Const

df.loc

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.

How it works

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.

Syntax

df.loc[row_indexer, column_indexer]

Parameters

NameTypeDescription
indexerlabel, list-like, slice, boolean array, alignable Series/Index, or callableRow 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.

Returns

A cross-section consisting of selected row(s) or column(s) from the DataFrame; the exact result type depends on the indexers.

Key points

  • Use loc to retrieve or assign groups of rows and columns using labels or boolean selection.
  • Its main indexing model is labels, with boolean arrays also supported.
  • Pass a list or array when selecting multiple, explicitly named labels.
  • Use label slices to select a contiguous label range.
  • A positional boolean mask must have the same length as the axis it filters.
  • A boolean Series can filter rows while pandas aligns its index to the target.
  • When an alignable Index is used, the result retains that Index as its selection index.

Common mistakes

  • Label-based slices include both boundary labels, unlike ordinary Python slices.
  • Numeric keys are still treated as index labels, not positional offsets; use iloc for integer-position access.
  • An alignable boolean Series is matched to the DataFrame index before it filters rows.

Example: Select and update by labels

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.

When to use it

Label-based selection

Retrieve specific records or fields by their index and column labels.

Boolean filtering

Keep rows satisfying a condition and optionally select particular columns.

Label-based assignment

Change selected cells or ranges without relying on positional offsets.

Inclusive label slicing

Select an inclusive range of ordered index or column labels.

  • DataFrame.iloc
  • DataFrame.at
  • DataFrame.iat
  • Series.loc

Source: pandas.DataFrame.loc#. Checked 2026-10-15.