pandas loc vs iloc: label-based vs position-based selection
verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated 2026-10-20
- tool
- pandas
- compares
- loc vs iloc
df.loc[...] selects by label: index values and column names, and a slice like "b":"d" includes "d". df.iloc[...] selects by integer position, like a Python list, and a slice 1:3 excludes position 3. They return the same rows only when the index happens to be 0, 1, 2, ….
Same DataFrame, different results
python -c '
import pandas as pd
df = pd.DataFrame({"x": [10, 20, 30, 40]}, index=[3, 2, 1, 0])
print("--- df.loc[1] (label 1)"); print(df.loc[1].tolist())
print("--- df.iloc[1] (second row)"); print(df.iloc[1].tolist())
print("--- df.loc[3:1] (labels 3 to 1, end included)"); print(df.loc[3:1].index.tolist())
print("--- df.iloc[0:2] (positions 0 and 1)"); print(df.iloc[0:2].index.tolist())'Output
--- df.loc[1] (label 1) [30] --- df.iloc[1] (second row) [20] --- df.loc[3:1] (labels 3 to 1, end included) [3, 2, 1] --- df.iloc[0:2] (positions 0 and 1) [3, 2]
Criterion by criterion
| Criterion | loc | iloc |
|---|---|---|
| Selects by | labels (index values, column names) | integer positions |
| Slice end | included: "b":"d" returns d | excluded: 1:3 returns positions 1 and 2 |
| Boolean mask | yes: df.loc[df.x > 10] | only a NumPy array or list, not a Series |
| Column selection | by name: df.loc[:, ["x"]] | by position: df.iloc[:, [0]] |
| Assignment | df.loc[mask, "x"] = 0 (the recommended way) | df.iloc[0, 0] = 0 |
| Missing label / position | KeyError | IndexError |
Rule of thumb
Use loc for almost everything, especially filtering and assigning (df.loc[df["a"] > 1, "b"] = 0). Use iloc when position is what you mean: the first row, the last five rows (df.iloc[-5:]), or the third column regardless of its name.
Sources
Related pages
errors · pandasSettingWithCopyWarning: A value is trying to be set on a copy of a slicepandas 2 warns SettingWithCopyWarning when you assign to a filtered DataFrame that may be a copy. Use .loc on the original or .copy(); pandas 3 removed it.cheat sheets · pandaspandas cheat sheet: read, select, filter, group and reshapepandas cheat sheet: read CSV and Parquet, select with loc and iloc, filter rows, add columns, group and aggregate, pivot, handle missing values and write files.commands · pandaspandas merge: join DataFrames on a key (inner, left, outer)pd.merge(left, right, on='id', how='left') joins DataFrames like SQL. how picks inner, left, right, outer or cross; validate= catches duplicated keys.