Home »
Python »
Python Programs
Python Pandas | How to create a MultiIndex with names of each of the index levels?
Learn how to create a MultiIndex with the names of each of the index levels 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.
pandas.MultiIndex.from_arrays() method
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. 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:
# 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:
# 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 »