To get the names of levels in MultiIndex – we use MultiIndex.names property. 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 –
# 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)
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']]
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Consider the below example –
Python code to get the levels in MultiIndex
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer