What is the difference between loc and iloc in pandas?
loc selects by label (index values and column names) and includes the end of a slice. iloc selects by integer position and excludes the end, like normal Python slicing.
Explain it simply
Think of a hostel. loc asks for room number 5. iloc asks for the first room in the corridor, whatever its number is. If rooms are numbered 5, 6, 7, then room 5 is also the first room, but room "1" does not exist.
Example
import pandas as pd
df = pd.DataFrame({"v": [10, 20, 30]}, index=[5, 6, 7])
print(df.loc[5, "v"]) # 10 (label 5)
print(df.iloc[0, 0]) # 10 (position 0, column 0)
print(df.loc[5:6].shape) # (2, 1) label slice includes 6
print(df.iloc[0:1].shape) # (1, 1) position slice excludes 1Key differences:
locslices are inclusive of the stop label;ilocslices are exclusive.locaccepts boolean masks:df.loc[df["v"] > 15, "v"].- Setting values safely uses loc:
df.loc[mask, "v"] = 0.
After filtering or sorting, the index no longer matches positions, which is where the two behave very differently.
What to say in the interview
"loc is label-based and inclusive, iloc is position-based and exclusive. I use loc with boolean masks to filter and assign, and iloc when I need the nth row. I avoid chained indexing like df[mask]["col"] = x, because it may not modify the original and triggers SettingWithCopy warnings."
Common mistakes
- Using df.loc[0] after sorting or filtering and expecting the first row.