For a DataFrame with the default RangeIndex, which rows do df.loc[0:2] and df.iloc[0:2] return?
Correct answer
A. loc returns rows 0, 1 and 2 inclusive, while iloc returns rows 0 and 1 only
12 views
A. loc returns rows 0, 1 and 2 inclusive, while iloc returns rows 0 and 1 only
12 views
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.
Asked in: NTS, PPSC IT, Interviews
Not sure why the answer is A? Ask here and get an explanation.