How to get the name of levels in MultiIndex in Python Pandas?

Learn, how to get the name of levels in MultiIndex? By IncludeHelp Last updated : April 10, 2023

MultiIndex Object

In Python Pandas, the MultiIndex object is the hierarchical analogue of the standard Index object which typically stores the axis labels in pandas objects. You can consider that MultiIndex is an array of unique tuples.

The pandas.MultiIndex.from_arrays() method is used to create a MultiIndex, and the names parameter is used to set names of each of the index levels.

Read: Create a MultiIndex with the names of each of the index levels

How to Get the names levels in MultiIndex?

As we have learned in the last example, that MultiIndex.levels property is used to get the levels in MultiIndex. To get the names of levels in MultiIndex, we use MultiIndex.names property.

Consider the below example –

Python program to get the levels in MultiIndex

# Import the pandas package
import pandas as pd

# Create arrays
cities = [
        ['New Delhi', 'Mumbai', 'Banglore', 'Kolkata'],
        ['New York', 'Los Angeles', 'Chicago', 'Houston']

# create a Multiindex using  from_arrays() 
mi = pd.MultiIndex.from_arrays(cities, names=('india_cities', 'usa_cities'))

# display the Multiindex
print("The MultiIndex...\n",mi)

# Get the levels in MultiIndex
print("The levels in MultiIndex...\n",mi.levels)


The MultiIndex...
 MultiIndex([('New Delhi',    'New York'),
            (   'Mumbai', 'Los Angeles'),
            ( 'Banglore',     'Chicago'),
            (  'Kolkata',     'Houston')],
           names=['india_cities', 'usa_cities'])
The levels in MultiIndex...
 [['Banglore', 'Kolkata', 'Mumbai', 'New Delhi'], ['Chicago', 'Houston', 'Los Angeles', 'New York']]

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.