MultiIndex Selection: xs() and swaplevel()
mediumpandas_manipulationGiven a DataFrame with a 2-level column MultiIndex (metric, year),
implement two selection functions.
xs_by_level(df, key, level)
Return the cross-section where the MultiIndex level equals key,
using df.xs(key, axis=1, level=level).
swaplevel_select(df, key)
Swap the two column levels with swaplevel(axis=1) and then index by key
to select all columns whose original level-1 value equals key.
Both functions must return the same result when called with the same key.
# df.columns is MultiIndex: (metric, year) e.g. ("Sales",2022), ("Offers",2022)
xs_by_level(df, 2022, level="year")
# Returns DataFrame with columns ["Sales","Offers"] (the 2022 slice)
Your solution
Edit xs_by_level and run the real pytest suite in your browser — no install required. Your code is saved locally.
Loading the Python runtime (first run only)…
Hints
Hint 1
df.xs(key, axis=1, level='year') returns all columns where the 'year' level equals key.
Hint 2
df.swaplevel(axis=1) swaps the two column-MultiIndex levels; then df[key] selects by the new level 0.
Hint 3
Both approaches return a DataFrame with a flat (non-multi) column index.