- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Get location for a sequence of labels in a MultiIndex
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]
Advertisements
To Continue Learning Please Login
Login with Google