Select rows by a named MultiIndex level in pandas with xs
Quick Overview
Write a pandas function that returns every row matching a key at a named level of a two-level MultiIndex and drops that level from the result. It tests DataFrame.xs, MultiIndex level handling, and how the selection behaves with missing keys or duplicate index entries.
Select rows by a named MultiIndex level in pandas with xs
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `cross_section(df, level_name, key)` where `df` has a 2-level row `MultiIndex`. Return every row whose value at index level `level_name` equals `key`.
Requirements:
- Select rows via `df.xs(key, level=level_name)`.
- Drop the selected level from the output index (the `xs` default).
- Preserve the original column order.
- Preserve the labels and order of the remaining index level.
Example:
```python
idx = pd.MultiIndex.from_tuples(
[("A", 1), ("A", 2), ("B", 1)],
names=["grp", "sub"],
)
df = pd.DataFrame({"v": [10, 20, 30]}, index=idx)
cross_section(df, "grp", "A")
# v
# sub
# 1 10
# 2 20 (index level 'grp' dropped)
```
```hint Try a missing key
Call your function with a key that does not appear in the level and look at what comes back. Decide whether that behavior is what a caller would expect.
```
### What a Strong Answer Covers
- Matching on the level by name and why that is safer than by position
- What the result index looks like once one of the two levels is dropped
- That column order and the order of the remaining labels are preserved
- How the function behaves for a missing key, a missing level name and duplicate index entries
### Follow-up Questions
- How would you keep the selected level in the result instead of dropping it?
- What happens when the index has duplicate entries, and how would you guard against an unexpected number of matching rows?
- How would you select several keys from the same level at once?
Overview: Write a pandas function that returns every row matching a key at a named level of a two-level MultiIndex and drops that level from the result. It tests DataFrame.xs, MultiIndex level handling, and how the selection behaves with missing keys or duplicate index entries.