What does df.xs(2021, level='year') return on a frame with a MultiIndex containing a year level?
A
The frame sorted by the year level, keeping only the first matching rows
B
The year level reset into an ordinary column of the same DataFrame
C
A grouped object that aggregates the values for 2021 by the other index level
D
A cross-section at one index level, with that level dropped from the result
Correct answer
Correct answer
D. A cross-section at one index level, with that level dropped from the result
14 views
⚔️
Challenge a friend on Pandas
Same MCQs, timed, live leaderboard. Send the link on WhatsApp – no sign-up needed.
Create challenge
Explanation
xs takes a cross-section of a MultiIndex: it selects every row whose year level equals 2021 and returns a frame with that level removed, so the result is indexed only by the remaining levels. Passing drop_level=False keeps the level in place. It is the readable alternative to a full .loc slice with slice(None) for the other levels.
Reference
Asked in: NTS, PPSC IT, Interviews
Doubts & discussionNot sure why the answer is D? Ask here and get an explanation.
Ask a doubt about this MCQ
‹ Previous MCQ A pattern capturing one or more digits is applied with Series.str.extract to a column where some values do not match. What appears in those rows? Next MCQ › A frame containing NaN values is reshaped with stack() and then unstack(). What is the result compared with the original?