What is the difference between label-based .loc and position-based .iloc for selecting data in a DataFrame?

Quick Overview

Asks how the pandas indexers .loc and .iloc differ when selecting rows and columns from a DataFrame, and when to reach for each one. Tests label versus position indexing, slice endpoints, boolean masks, and the index pitfalls that appear after sorting or filtering.

What is the difference between label-based .loc and position-based .iloc for selecting data in a DataFrame?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What is the difference between label-based `.loc` and position-based `.iloc` for selecting data in a `DataFrame`? ```hint Try a sorted frame Take a DataFrame with the default 0 to n-1 index, sort it by one of its columns, and work out what `df.loc[0]` and `df.iloc[0]` each return. ``` ### What a Strong Answer Covers - What each indexer keys on, and which kinds of selectors each one accepts - How each one treats the end of a slice - When each one is the natural choice, with a concrete case for both - The situation where the same integer picks different rows, and why it happens ### Follow-up Questions - Why does `df[df["score"] < 70]["score"] = 70` leave `df` unchanged, and how do you write it correctly? - What happens if you pass a boolean Series to `.iloc`, and how do you make that selection work? - How do `.at` and `.iat` relate to `.loc` and `.iloc`, and when are they worth using? - What does plain `[]` indexing do on a DataFrame or a Series, and why can it be ambiguous?

Overview: Asks how the pandas indexers .loc and .iloc differ when selecting rows and columns from a DataFrame, and when to reach for each one. Tests label versus position indexing, slice endpoints, boolean masks, and the index pitfalls that appear after sorting or filtering.

General logo
General
Nov 25, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

What is the difference between label-based .loc and position-based .iloc for selecting data in a DataFrame?

What a Strong Answer Covers Guidance

  • What each indexer keys on, and which kinds of selectors each one accepts
  • How each one treats the end of a slice
  • When each one is the natural choice, with a concrete case for both
  • The situation where the same integer picks different rows, and why it happens

Follow-up Questions Guidance

  • Why does df[df["score"] < 70]["score"] = 70 leave df unchanged, and how do you write it correctly?
  • What happens if you pass a boolean Series to .iloc , and how do you make that selection work?
  • How do .at and .iat relate to .loc and .iloc , and when are they worth using?
  • What does plain [] indexing do on a DataFrame or a Series, and why can it be ambiguous?