1. Home
  2. Data Science
  3. Pandas
  4. For a DataFrame with the default RangeIndex, which rows do…

Added 30 Nov -0001

For a DataFrame with the default RangeIndex, which rows do df.loc[0:2] and df.iloc[0:2] return?

  1. loc returns rows 0, 1 and 2 inclusive, while iloc returns rows 0 and 1 only Correct answer
  2. Both return rows 0, 1 and 2
  3. loc returns rows 0 and 1, while iloc returns 0, 1 and 2
  4. Both return rows 0 and 1, because slices always exclude the endpoint

Correct answer

A. loc returns rows 0, 1 and 2 inclusive, while iloc returns rows 0 and 1 only

12 views

MCQSEXAM

Explanation

Label versus positional indexing: .loc slices on labels and includes the stop label, so 0:2 covers three rows, whereas .iloc slices on integer positions with the usual Python half-open rule and covers two. The distinction bites when the index is not a clean RangeIndex or is sorted descending. Use .loc for label-safe selection and .iloc when position is what you mean.

Reference

Asked in: NTS, PPSC IT, Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? 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