Skip to main content
  1. Posts/

The Rule Everyone Misses: loc vs iloc in Pandas

··242 words·2 mins·

🐼 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?

SituationUse
Meaningful index (ID, name)loc
I want the first N rowsiloc
Duplicate or messy indexiloc
Boolean filteringloc

⚠️ Slicing difference:

  • loc[101:103] → includes row 103
  • iloc[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.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano