Skip to content

/compare/pandas/loc-vs-iloc

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

bash
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

Criterionlociloc
Selects bylabels (index values, column names)integer positions
Slice endincluded: "b":"d" returns dexcluded: 1:3 returns positions 1 and 2
Boolean maskyes: df.loc[df.x > 10]only a NumPy array or list, not a Series
Column selectionby name: df.loc[:, ["x"]]by position: df.iloc[:, [0]]
Assignmentdf.loc[mask, "x"] = 0 (the recommended way)df.iloc[0, 0] = 0
Missing label / positionKeyErrorIndexError

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