Python Pandas - Get the Names of levels in MultiIndex

To get the names of levels in MultiIndex, use the MultiIndex.names property in Pandas. A MultiIndex is a multi-level, or hierarchical, index object that allows you to work with higher dimensional data in a lower dimensional form.

Creating a MultiIndex

First, let's create a MultiIndex using arrays. The names parameter sets the names for each index level ?

import pandas as pd

# Create arrays for MultiIndex
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

# Create MultiIndex with named levels
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

# Display the MultiIndex
print("The Multi-index...")
print(multiIndex)
The Multi-index...
MultiIndex([(1, 'John'),
            (2, 'Tim'),
            (3, 'Jacob'),
            (4, 'Chris'),
            (5, 'Keiron')],
           names=['ranks', 'student'])

Getting Level Names

Use the names property to retrieve the names of all levels in the MultiIndex ?

import pandas as pd

arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

# Get the names of levels in MultiIndex
print("The names of levels in Multi-index...")
print(multiIndex.names)
The names of levels in Multi-index...
['ranks', 'student']

Complete Example

Here's a complete example showing MultiIndex creation and accessing both names and levels ?

import pandas as pd

# Create arrays for MultiIndex
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

# Create MultiIndex with named levels
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

# Display the MultiIndex
print("The Multi-index...")
print(multiIndex)

# Get the names of levels in MultiIndex
print("\nThe names of levels in Multi-index...")
print(multiIndex.names)

# Get the levels in MultiIndex
print("\nThe levels in Multi-index...")
print(multiIndex.levels)
The Multi-index...
MultiIndex([(1, 'John'),
            (2, 'Tim'),
            (3, 'Jacob'),
            (4, 'Chris'),
            (5, 'Keiron')],
           names=['ranks', 'student'])

The names of levels in Multi-index...
['ranks', 'student']

The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]

Conclusion

The MultiIndex.names property returns a list of level names in a MultiIndex. This is useful for identifying and working with hierarchical data structures in Pandas.

Updated on: 2026-03-26T17:20:33+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements