
🐼 Using loc or iloc in Pandas? The difference is simpler than you think.
If you work with DataFrames in Python, you’ve probably been confused by these two operators at some point. The rule is simple:
loc→ selects by labels (index name or column name)iloc→ selects by integer position (like indexing a list)
💡 Practical examples:
# loc: by label
df.loc[102] # row with index 102
df.loc[101:103, 'math'] # label range, end included
# iloc: by position
df.iloc[1] # second row (position 1)
df.iloc[0:3, [0, 1, 3]] # rows 0–2, columns by position📌 When to use each?
| Situation | Use |
|---|---|
| Meaningful index (ID, name) | loc |
| I want the first N rows | iloc |
| Duplicate or messy index | iloc |
| Boolean filtering | loc |
⚠️ Slicing difference:
loc[101:103]→ includes row 103iloc[0:3]→ excludes position 3 (same as Python lists)
💡 Explanation in a nutshell#
loc works with the labels you see in the DataFrame index, while iloc works with numeric positions (0, 1, 2…), just like a list. If your index is numeric starting from 0, they may look the same — but once you change the index, loc and iloc can give completely different results.
More information at the link 👇
Also published on LinkedIn.

