Pick rows by integer position from a list of records — first collecting target records via a position list, then extracting a field. With pandas, df.iloc accepts a slice or a list of integers and returns a sub-DataFrame in one step.

By hand

With pandas

df.iloc[0:2] selects a contiguous slice by position (end-exclusive). df.iloc[[0, 2]] selects an arbitrary list of positions. Both return a sub-DataFrame preserving the original column structure.

naive.py
# trace: ignore records
records = [
    {'name': 'al', 'age': 20},
    {'name': 'bo', 'age': 25},
    {'name': 'cy', 'age': 22},
    {'name': 'di', 'age': 28},
]
positions = [0, 2]
selected = []
for i in positions:
    selected.append(records[i])
names = []
for r in selected:
    names.append(r['name'])
print('RESULT:', names)
library.py
import pandas as pd
from dalib.display import set_display
set_display()

records = [
    {'name': 'al', 'age': 20},
    {'name': 'bo', 'age': 25},
    {'name': 'cy', 'age': 22},
    {'name': 'di', 'age': 28},
]
df = pd.DataFrame(records)
slice2 = df.iloc[0:2]
by_pos = df.iloc[[0, 2]]
print('slice [0:2] names:', slice2['name'].tolist())
print('index [0,2] names:', by_pos['name'].tolist())
print('index [0,2] shape:', by_pos.shape)
print('RESULT:', by_pos['name'].tolist())
slice [0:2] names: ['al', 'bo']
index [0,2] names: ['al', 'cy']
index [0,2] shape: (2, 2)
RESULT: ['al', 'cy']

Implementation notes

  • iloc is positional: it counts rows from 0 regardless of the index label. Slices are end-exclusive (iloc[0:2] → rows 0 and 1), exactly like Python list slicing.
  • Passing a list (iloc[[0, 2]]) selects non-contiguous rows; passing a slice (iloc[0:2]) selects a contiguous range. The return type is a DataFrame in both cases.
  • iloc also accepts a second argument for column positions: df.iloc[0:2, 0] returns the first column of the first two rows as a Series.
  • Contrast with loc (see select-rows-loc): loc uses index labels, not integer positions, and its slices are end-inclusive.