Select rows in pandas MultiIndex DataFrame
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
A MultiIndex (hierarchical index) DataFrame in pandas has two or more index levels, allowing you to represent higher-dimensional data in a 2D table. Selecting rows from a MultiIndex DataFrame uses different syntax than a single-index DataFrame — you can select by level, cross-section, or boolean conditions using .loc, .xs(), IndexSlice, and query().
Creating a MultiIndex DataFrame
Select by First Level (Outer Index)
Select by Both Levels
Select by Second Level with xs()
xs() (cross-section) selects rows by a value at a specific level:
Slicing with IndexSlice
pd.IndexSlice enables intuitive slicing on MultiIndex DataFrames:
Boolean Filtering
Using query() with MultiIndex
Resetting and Setting Index
Selecting Specific Columns with MultiIndex
GroupBy Operations on MultiIndex
Swapping and Reordering Levels
Common Pitfalls
- Unsorted index for slicing: Slicing with
locon a MultiIndex requires the index to be sorted. Calldf.sort_index()before slicing, or you get aUnsortedIndexError. - Tuple vs list in loc:
df.loc[('US', 'NYC')]selects one row (tuple = single key).df.loc[['US', 'UK']]selects multiple first-level keys (list = multiple keys). Mixing these up gives unexpected results. - Dropping levels: After selecting by one level (e.g.,
df.loc['US']), that level is dropped from the result. Usedrop_level=Falseinxs()to keep it:df.xs('US', level='country', drop_level=False). - Performance with large DataFrames: Repeated
get_level_values()calls in loops are slow. For bulk filtering, reset the index, filter on columns, and set the index back. - String vs numeric index: If index levels are strings,
df.loc[1]will fail. Ensure you use the correct type for indexing. Check withdf.index.get_level_values(0).dtype.
Summary
- Use
df.loc['key']to select by the outer (first) level of a MultiIndex - Use
df.loc[('level1', 'level2')]to select by both levels - Use
df.xs('value', level='name')to select by any level, including inner levels - Use
pd.IndexSlicefor intuitive slicing across multiple levels - Use
df.query('level_name == "value"')for readable filtering on index levels - Always sort the index with
df.sort_index()before slicing
Related reading
- Selecting a row of pandas series/dataframe by integer index
- Selecting multiple columns in a Pandas dataframe
- Selecting with complex criteria from pandas.DataFrame
- Selecting/excluding sets of columns in pandas
- Selenium using Python - Geckodriver executable needs to be in PATH
- Send HTML emails with Python
- Sending metrics from kafka to grafana
- Sentimental analysis using apache mahout
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.