Pandas Label Selection with loc
loc selects labels, not numerical positions. Use it when the question names a drop-off identifier or a column rather than an offset in the current table.
How it works
A label slice includes its stop label when that endpoint is present and the index supports the requested slice. That differs from a normal positional Python slice. Selecting one scalar coordinate, one row or a list of rows produces different result types. Check the required index properties before relying on a label range, especially when labels are duplicated or unsorted.
Run the code
Select Try in playground to load the complete editable source. Nothing executes until you choose Run. The browser uses Pyodide 0.27.7, Pandas 2.2.3 and NumPy 2.0.2. Each ordinary execution starts a fresh isolated runtime. The tables are fictional and do not use personal files.
For local work, use a separate virtual environment and run python label-selection.py. Download the complete source. The reviewed local environment uses Python 3.12.14, Pandas 3.0.6 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with Pandas 2.2.3 and NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import pandas as pd
import numpy as np
df = pd.DataFrame({
"drop_id": [101, 102, 103, 104],
"point": ["north", "south", "north", "south"],
"material": ["leaves", "food", "food", "leaves"],
"kg": [12., 8., 6., 10.],
"bags": pd.array([3, 2, 1, 2], dtype="Int64"),
"day": ["2026-10-01", "2026-10-01", "2026-10-02", "2026-10-02"],
})
table = df.set_index("drop_id")
print(table.loc[[101, 103], "kg"].tolist())
print(table.loc[101:102, "kg"].tolist())
print(float(table.at[104, "kg"]))
Expected result
[12.0, 6.0] [12.0, 8.0] 10.0
The range includes drop-off 102, while the explicit list selects 101 and 103. at is useful for a known scalar label pair when the identity contract guarantees the intended lookup. It is not a substitute for checking index uniqueness.
Use Pandas’s official reference for precise contracts, supported versions and numerical limitations.