Advertisements
Advertisements
Question
Which of the following Python commands selects the first 3 rows of a DataFrame df, assuming that labelled index are consecutive integers starting from 0?
Options
df.loc[:3]df.loc[:2]df.loc[0:4]df.loc[1:4]
MCQ
Advertisements
Solution
df.loc[:2]
Explanation:
In pandas, .loc[] selects rows by label and includes the end label.
Since the index starts at 0, the first three rows have labels 0, 1, and 2.
So df.loc[:2] correctly selects these three rows (0, 1, and 2).
shaalaa.com
Is there an error in this question or solution?
