Two accessors select rows and columns at once. loc selects by label; iloc selects by integer position. They're the workhorses of precise selection.
loc vs iloc
| Accessor | Selects by | Example |
|---|---|---|
loc | Row/column labels | df.loc[0, "name"] |
iloc | Integer positions | df.iloc[0, 1] |
df.loc[0, "name"] # a single cell by labeldf.loc[df["package"] > 7, "name"] # filtered rows, one column — very commondf.loc[:, ["name", "package"]] # all rows, chosen columnsdf.iloc[0] # first row by positiondf.iloc[0:3, 0:2] # first 3 rows, first 2 columns
Setting values
Key takeaways
- 01loc selects by label; iloc selects by integer position.
- 02df.loc[rows, cols] is the precise workhorse — combine a row mask with column names.
- 03iloc uses 0-based positions and half-open ranges like NumPy.
- 04Set values through .loc to avoid the chained-assignment trap.
