Python Pandas - Return vector of label values using level name in the MultiIndex

PythonServer Side ProgrammingProgramming

To return vector of label values using level name in the MultiIndex, use the MultiIndex.get_level_values() method in Pandas.

At first, import the required libraries −

import pandas as pd

MultiIndex is a multi-level, or hierarchical, index object for pandas objects −

multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])

Display the MultiIndex −

print("The MultiIndex...
",multiIndex)

Get level values using level name "Two" −

print("
Level values using level name...
",multiIndex.get_level_values("Two"))

Example

Following is the code −

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])

# display the MultiIndex
print("The MultiIndex...
",multiIndex) # get the levels in MultiIndex print("
The levels in MultiIndex...
",multiIndex.levels) # get level values using level name "Two" print("
Level values using level name...
",multiIndex.get_level_values("Two"))

Output

This will produce the following output −

The MultiIndex...
MultiIndex([('p', 's'),
            ('q', 't'),
            ('r', 'r'),
            ('r', 'v'),
            ('s', 'w'),
            ('s', 'x')],
            names=['One', 'Two'])

The levels in MultiIndex...
   [['p', 'q', 'r', 's'], ['r', 's', 't', 'v', 'w', 'x']]

Level values using level name...
   Index(['s', 't', 'r', 'v', 'w', 'x'], dtype='object', name='Two')
raja
Updated on 19-Oct-2021 08:36:19

Advertisements