Home »
Python »
Python Programs
Create a MultiIndex with names of each of the index levels in Python Pandas
Learn how to create a MultiIndex with the names of each of the index levels 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.
How to create a MultiIndex with names of each of the index levels?
To create a MultiIndex, we use pandas.MultiIndex.from_arrays() method, the names parameter is used to set names of each of the index levels. This method accepts two parameters arrays and names.
First, we have to import the pandas library:
import pandas as pd
Consider the below examples –
Example 1: MultiIndex with names of each of the index levels
# Import the pandas package
import pandas as pd
# Create arrays
arrays = [[101, 102, 103], ['Shivang', 'Radib', 'Monika']]
# Create a Multiindex using from_arrays()
mi = pd.MultiIndex.from_arrays(arrays, names=('ids', 'student'))
# display the Multiindex
print("The MultiIndex...\n",mi)
# Get the names of levels in Multiindex
print("The names of levels in Multi-index...\n",mi.names)
Output
The MultiIndex...
MultiIndex([(101, 'Shivang'),
(102, 'Radib'),
(103, 'Monika')],
names=['ids', 'student'])
The names of levels in Multi-index...
['ids', 'student']
Example 2: MultiIndex with names of each of the index levels
# 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 names of levels in MultiIndex
print("The names of levels in Multi-index...\n",mi.names)
Output
The MultiIndex...
MultiIndex([('New Delhi', 'New York'),
( 'Mumbai', 'Los Angeles'),
( 'Banglore', 'Chicago'),
( 'Kolkata', 'Houston')],
names=['india_cities', 'usa_cities'])
The names of levels in Multi-index...
['india_cities', 'usa_cities']
Python Pandas Programs »