ADVERTISEMENT
ADVERTISEMENT

Python Pandas | How to get the levels in MultiIndex?

Learn how to get the levels in MultiIndex in Python Pandas?
Submitted by IncludeHelp, on March 16, 2022

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

Get the levels in MultiIndex

MultiIndex.levels property is used to get the levels in MultiIndex. To work with MultiIndex in Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Consider the below example –

Python code to get the names of 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)

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

Output:

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']]
The names of levels in MultiIndex...
 ['india_cities', 'usa_cities']

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.