Selecting and Filtering
Select Rows by Label (loc)
Build a label-to-index map from a parallel labels list, then look up rows by
string key. With pandas, a DataFrame can carry a named index, and df.loc
selects rows by those labels directly — no manual mapping needed.
By hand
With pandas
pd.DataFrame(records, index=labels) assigns string labels as the row index.
df.loc[['p', 'r']] selects those rows by label and returns a sub-DataFrame
with the matching index.
naive.py
# trace: ignore records
labels = ['p', 'q', 'r', 's']
records = [
{'name': 'al', 'age': 20},
{'name': 'bo', 'age': 25},
{'name': 'cy', 'age': 22},
{'name': 'di', 'age': 28},
]
label_to_idx = {}
for i in range(len(labels)):
label_to_idx[labels[i]] = i
keys = ['p', 'r']
names = []
for k in keys:
idx = label_to_idx[k]
names.append(records[idx]['name'])
print('RESULT:', names)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
labels = ['p', 'q', 'r', 's']
records = [
{'name': 'al', 'age': 20},
{'name': 'bo', 'age': 25},
{'name': 'cy', 'age': 22},
{'name': 'di', 'age': 28},
]
df = pd.DataFrame(records, index=labels)
selected = df.loc[['p', 'r']]
print('index:', selected.index.tolist())
print('names:', selected['name'].tolist())
print('shape:', selected.shape)
print('RESULT:', selected['name'].tolist())
index: ['p', 'r']
names: ['al', 'cy']
shape: (2, 2)
RESULT: ['al', 'cy']
Implementation notes
locis label-based: it looks up rows by index value, not by integer position. If the index is['p', 'q', 'r', 's'], thendf.loc['r']returns the row labelled'r'regardless of its physical position.- Label slices with
locare end-inclusive:df.loc['p':'r']returns rowsp,q, andr. This differs fromilocslices, which are end-exclusive. - Passing a list (
loc[['p', 'r']]) selects specific labels in the given order; the result index matches the requested order, not the original order. localso accepts column labels as a second argument:df.loc[['p', 'r'], 'name']returns just thenamecolumn for those rows as a Series.- Contrast with
iloc(seeselect-rows-iloc): useilocfor position-based selection,locfor label-based selection.