ZetCode

Pandas MultiIndex

last modified November 17, 2026 Python 3.15

A MultiIndex, also called a hierarchical index, is an index with more than one level of labels. Instead of identifying each row by a single value, we identify it by a tuple of values, such as a city together with a year. This is useful for data that has a natural nesting, like sales per city per year, because it lets us select a whole city or a whole year with one short expression.

In this article we build MultiIndexDataFrames in two ways, then look at the tools for selecting and reshaping them: loc with tuples, xs, swaplevel, droplevel, sort_index by level, and partial slicing. All examples were run with pandas 3.1.1.

Hierarchical labels

The most direct way to create a hierarchical index is MultiIndex.from_tuples. We pass a list of tuples, where each tuple holds one label per level, and give the levels names. The name of each level appears above the data in the printed table, which makes the two levels easy to tell apart. Rows whose first label is the same are grouped visually because that label is printed only once.

multiindex_from_tuples.py
import pandas as pd

tuples = [('A', 2024), ('A', 2025), ('B', 2024), ('B', 2025)]
index = pd.MultiIndex.from_tuples(tuples, names=['city', 'year'])
df = pd.DataFrame([10, 20, 30, 40], index=index, columns=['sales'])
print(df)

The result has a city level and a year level. The four sales figures are indexed by (A, 2024), (A, 2025), (B, 2024) and (B, 2025). The pair of labels, not either label alone, identifies one row.

$ python multiindex_from_tuples.py
           sales
city year       
A    2024     10
     2025     20
B    2024     30
     2025     40

Setting a MultiIndex from columns

Often the information for the index is already present as ordinary columns. The set_index method moves one or more columns into the index. We pass a list of two column names to get two levels; those columns disappear from the body of the table and become the row labels. This is the commonest way to turn a flat table into a hierarchical one.

multiindex_set_index.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B'],
    'year': [2024, 2025, 2024, 2025],
    'sales': [10, 20, 30, 40]
})
print(df.set_index(['city', 'year']))

The table looks exactly like the one built with from_tuples. The difference is only how we got there: here the city and year values started out as data columns.

$ python multiindex_set_index.py
           sales
city year       
A    2024     10
     2025     20
B    2024     30
     2025     40

Selecting with loc and tuples

The loc label-based indexer accepts a tuple with one label per level, in the same order as the levels. We write df.loc[(city, year), column] to reach a single cell. For the full range of label-based selection see the Pandas loc function tutorial.

multiindex_loc.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B'],
    'year': [2024, 2025, 2024, 2025],
    'sales': [10, 20, 30, 40]
}).set_index(['city', 'year'])
print(df.loc[('A', 2025), 'sales'])

The tuple ('A', 2025) picks the row for city A in year 2025, and 'sales' picks the column. The value stored there is 20. Supplying fewer labels than there are levels performs a partial selection, which we look at later.

$ python multiindex_loc.py
20

Cross-sections with xs

A cross-section is a slice taken across one level of a hierarchical index. The xs method takes a label and a level name, and drops that level from the result. Asking for xs('A', level='city') returns every year recorded for city A, with year left as a simple index.

multiindex_xs.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B'],
    'year': [2024, 2025, 2024, 2025],
    'sales': [10, 20, 30, 40]
}).set_index(['city', 'year'])
print(df.xs('A', level='city'))

Only the two rows belonging to city A remain. Because the city level was removed, the index now shows just year with the values 2024 and 2025 and their sales of 10 and 20.

$ python multiindex_xs.py
      sales
year       
2024     10
2025     20

Swapping and dropping levels

The order of the levels is not fixed. swaplevel exchanges two levels, which changes the grouping of the printed rows. droplevel removes a level entirely, leaving the remaining labels as a single index. These methods return a new DataFrame; the original is unchanged.

multiindex_levels.py
import pandas as pd

df = pd.DataFrame({
    'city': ['A', 'A', 'B', 'B'],
    'year': [2024, 2025, 2024, 2025],
    'sales': [10, 20, 30, 40]
}).set_index(['city', 'year'])

print(df.swaplevel())
print()
print(df.droplevel('city'))

The first table is grouped by year now, with city as the inner level. The second table keeps only year: since two cities share each year, the remaining index contains repeated labels such as 2024 twice. Dropping a level does not merge those rows; it only shortens the label.

$ python multiindex_levels.py
           sales
year city       
2024 A        10
2025 A        20
2024 B        30
2025 B        40

      sales
year       
2024     10
2025     20
2024     30
2025     40

Sorting by a level

sort_index normally sorts by the outermost level. With a MultiIndex we can name a specific level through the level parameter, so the rows are ordered by the labels of our choice. The other labels travel with their rows, so the data stays intact.

multiindex_sort.py
import pandas as pd

tuples = [('B', 2025), ('A', 2024), ('B', 2024), ('A', 2025)]
index = pd.MultiIndex.from_tuples(tuples, names=['city', 'year'])
df = pd.DataFrame([40, 10, 30, 20], index=index, columns=['sales'])
print(df.sort_index(level='city'))

The unsorted index started with B, but the output is ordered by the city level: both A rows come first, then both B rows. Within each city the years keep their original order because we sorted by only one level.

$ python multiindex_sort.py
           sales
city year       
A    2024     10
     2025     20
B    2024     30
     2025     40

Partial slicing

Partial slicing means selecting rows by giving labels for only the outer levels of a MultiIndex. When we write df.loc['A'] on a two-level index, Pandas keeps every row whose first label is A and drops that level from the result. It is a compact alternative to xs for the outermost level.

multiindex_partial.py
import pandas as pd

tuples = [('A', 2024), ('A', 2025), ('B', 2024), ('B', 2025)]
index = pd.MultiIndex.from_tuples(tuples, names=['city', 'year'])
df = pd.DataFrame([10, 20, 30, 40], index=index, columns=['sales'])
print(df.loc['A'])

The result contains the two rows for city A, indexed by year alone. Giving just one label worked because it matched the first level; to select by the second level instead we use xs with level='year'.

$ python multiindex_partial.py
      sales
year       
2024     10
2025     20

Source

Pandas MultiIndex Documentation, Pandas DataFrame.xs Documentation, and Pandas Advanced Indexing Documentation

In this article we have built hierarchical indexes with MultiIndex.from_tuples and set_index, then selected and reshaped rows with loc tuples, xs, swaplevel, droplevel, sort_index by level and partial slicing. To learn more about label-based selection in general see the Pandas loc function tutorial, and for the flat index basics see Pandas index.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.