Python Pandas | Set levels on a MultiIndex

Learn, how to set levels on a MultiIndex in Python Pandas? 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 Set levels on a MultiIndex?

The pandas.MultiIndex.set_levels() method is used to set new levels on a MultiIndex.

Syntax

MultiIndex.set_levels(levels, level=None, inplace=None, verify_integrity=True)

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

import pandas as pd

Python program to set levels on a MultiIndex

# Import the pandas package
import pandas as pd

# Create arrays
employees = [
        ['E101', 'E102', 'E102', 'E103'],
        ['Alex', 'Alvin', 'Deniel', 'Jenny']
    ]

# create a Multiindex using  from_arrays() 
mi = pd.MultiIndex.from_arrays(employees, names=('emp_ids', 'names'))

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

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

# set the levels in MultiIndex
print("Setting new levels...\n",
    mi.set_levels([['e111', 'e112', 'e113', 'e114'], 
    ['Angelina', 'Emma', 'Kristen', 'Gal']]))

Output

The MultiIndex...
 MultiIndex([('E101',   'Alex'),
            ('E102',  'Alvin'),
            ('E102', 'Deniel'),
            ('E103',  'Jenny')],
           names=['emp_ids', 'names'])

The levels in MultiIndex...
 [['E101', 'E102', 'E103'], ['Alex', 'Alvin', 'Deniel', 'Jenny']]

Setting new levels...
 MultiIndex([('e111', 'Angelina'),
            ('e112',     'Emma'),
            ('e112',  'Kristen'),
            ('e113',      'Gal')],
           names=['emp_ids', 'names'])

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.