1. Home
  2. Data Science
  3. Pandas
  4. What is the difference between df.loc[2] and df.iloc[2]?

Added 30 Nov -0001

What is the difference between df.loc[2] and df.iloc[2]?

  1. Both address the row whose label equals 2
  2. loc works only on columns, iloc only on rows
  3. loc uses the index label 2; iloc uses position 2 Correct answer
  4. loc uses position 2; iloc uses the index label 2

Correct answer

C. loc uses the index label 2; iloc uses position 2

14 views

MCQSEXAM

Explanation

loc is label-based and matches the value stored in the index, while iloc is positional and counts from zero regardless of labels. When the index is the default RangeIndex starting at 0 the results coincide, which hides the difference until data is filtered or sorted and the index becomes non-contiguous. Both accept slice notation, but loc slices include the endpoint whereas iloc slices exclude it.

Reference

Asked in: NTS, PPSC IT, Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More Pandas MCQs

Practise all Pandas MCQs

Similar MCQs