Select rows by the inner MultiIndex level in pandas with IndexSlice, keeping both levels

Quick Overview

Write a pandas function that selects every row whose inner MultiIndex level matches a key, across all outer groups, while keeping both index levels. It tests pd.IndexSlice with .loc, how this differs from xs, and how missing keys and unsorted indexes behave.

Select rows by the inner MultiIndex level in pandas with IndexSlice, keeping both levels

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

Implement `slice_multiindex(df, second_key)`. `df` has a 2-level row `MultiIndex` (level 0 `'group'`, level 1 `'item'`). Return every row, across all groups, whose `'item'` equals `second_key`. Requirements: - Use `idx = pd.IndexSlice` and `df.loc[idx[:, second_key], :]`. - Keep both index levels on the output (unlike `xs`, do not drop level 1). - Preserve the original column order and relative row order. - Return a new `DataFrame`: do not mutate the input. Example: ```python idx = pd.MultiIndex.from_tuples( [('a','x'),('a','y'),('b','x'),('b','y')], names=['group','item']) df = pd.DataFrame({'v': [1, 2, 3, 4]}, index=idx) slice_multiindex(df, 'x') # v # group item # a x 1 # b x 3 (MultiIndex preserved) ``` ```hint Think about sorting Before you reach for `sort_index()`, check whether it would change the row order the task asks you to keep. ``` ### What a Strong Answer Covers - How `pd.IndexSlice` builds the selector and what each `:` selects - Why the result keeps both index levels, compared with `xs` - That row order and column order are preserved and the input is left unchanged - What happens when `second_key` is absent from the `item` level ### Follow-up Questions - How does this differ from `df.xs(second_key, level='item')`? - What happens if `second_key` does not exist in level 1? - Why might the index need sorting before slicing?

Overview: Write a pandas function that selects every row whose inner MultiIndex level matches a key, across all outer groups, while keeping both index levels. It tests pd.IndexSlice with .loc, how this differs from xs, and how missing keys and unsorted indexes behave.

General logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

Implement slice_multiindex(df, second_key). df has a 2-level row MultiIndex (level 0 'group', level 1 'item'). Return every row, across all groups, whose 'item' equals second_key.

Requirements:

  • Use idx = pd.IndexSlice and df.loc[idx[:, second_key], :] .
  • Keep both index levels on the output (unlike xs , do not drop level 1).
  • Preserve the original column order and relative row order.
  • Return a new DataFrame : do not mutate the input.

Example:

idx = pd.MultiIndex.from_tuples(
    [('a','x'),('a','y'),('b','x'),('b','y')],
    names=['group','item'])
df = pd.DataFrame({'v': [1, 2, 3, 4]}, index=idx)

slice_multiindex(df, 'x')
#              v
# group item
# a     x      1
# b     x      3   (MultiIndex preserved)

What a Strong Answer Covers Guidance

  • How pd.IndexSlice builds the selector and what each : selects
  • Why the result keeps both index levels, compared with xs
  • That row order and column order are preserved and the input is left unchanged
  • What happens when second_key is absent from the item level

Follow-up Questions Guidance

  • How does this differ from df.xs(second_key, level='item') ?
  • What happens if second_key does not exist in level 1?
  • Why might the index need sorting before slicing?