Python Pandas - Get location for a sequence of labels in a MultiIndex

PythonServer Side ProgrammingProgramming

To get location for a sequence of labels in a MultiIndex, use the MutiIndex.get_locs() 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('pqrrst'), list('kytssp')])

Display the MultiIndex −

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

Get the location for a sequence of labels −

print("\nGet the locations in MultiIndex...\n",multiIndex.get_locs('s'))

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('pqrrst'), list('kytssp')])

# display the MultiIndex
print("The MultiIndex...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)

# Get the location for a sequence of labels
print("\nGet the locations in MultiIndex...\n",multiIndex.get_locs('s'))

Output

This will produce the following output −

The MultiIndex...
MultiIndex([('p', 'k'),
            ('q', 'y'),
            ('r', 't'),
            ('r', 's'),
            ('s', 's'),
            ('t', 'p')],
           )

The levels in MultiIndex...
   [['p', 'q', 'r', 's', 't'], ['k', 'p', 's', 't', 'y']]

Get the locations in MultiIndex...
   [4]
raja
Published on 19-Oct-2021 08:14:16

Advertisements