Q:

Python Pandas | How to create a MultiIndex with names of each of the index levels?

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python Pandas | How to get the levels in MultiInde... >>