w3resource

Pandas MultiIndex slicing with loc

Pandas: Advanced Indexing and Slicing Exercise-14 with Solution

MultiIndex Slicing with loc:

Write a Pandas program that uses .loc to slice a MultiIndex DataFrame.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'A': [1, 6, 8, 3, 7],
    'B': [5, 2, 9, 4, 1],
    'C': ['one', 'one', 'two', 'two', 'one']
})

# Set MultiIndex
df = df.set_index(['C', 'A'])

# Sort the MultiIndex
df = df.sort_index()

# Slice MultiIndex DataFrame using .loc
result = df.loc['one':'two']
print(result)

Output:

       B
C   A   
one 1  5
    6  2
    7  1
two 3  4
    8  9

Explanation:

  • Import pandas library.
  • Create a DataFrame with columns 'A', 'B', and 'C'.
  • Set a MultiIndex using columns 'C' and 'A'.
  • Sort the MultiIndex to enable slicing.
  • Use .loc to slice the MultiIndex DataFrame from 'one' to 'two'.
  • Print the results.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Advanced Boolean indexing in Pandas DataFrame.
Next: Pandas - Conditional Selection with MultiIndex.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-multiindex-slicing-with-loc.php