loc selects by label; iloc selects by integer position. Mastering both prevents off-by-one bugs and SettingWithCopy warnings.
loc — label-based
import pandas as pd
df = pd.DataFrame({'x': [10, 20, 30]}, index=['a', 'b', 'c'])
print(df.loc['b']) # row label
print(df.loc['a':'c', 'x']) # slice inclusive on labels
iloc — position-based
print(df.iloc[0]) # first row
print(df.iloc[0:2, 0]) # rows 0-1, col 0
Setting values
df.loc[mask, 'col'] = value is the safe pattern for conditional updates. Boolean masks work in both loc row selection and filtering.
Important interview questions and answers
- Q: loc slice inclusive?
A: Label slices include both endpoints—unlike Python iloc slices which exclude the stop index. - Q: When iloc?
A: When you need position regardless of index labels—loops, head/tail patterns, unknown index.
Self-check
- Get row at integer position 2 with iloc.
- Update rows where a column exceeds a threshold using loc.
Tip: When lost, print df.index and df.columns before choosing loc vs iloc.
Interview prep
- loc vs iloc?
loc uses labels (inclusive slices); iloc uses integer positions.
- Safe update?
df.loc[mask, 'col'] = value—avoids SettingWithCopyWarning.