w3resource

Slice DataFrame with MultiIndex in Pandas


4. Slice DataFrame Based on MultiIndex Levels

Write a Pandas program to slice DataFrame based on MultiIndex levels.

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

# Slice DataFrame
result = df.loc['one']
print(result)

Output:

     B
A   
1  5
6  2
7  1

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Set a MultiIndex using columns 'C' and 'A'.
  • Slice DataFrame for index level 'one'.
  • Print the results.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to slice a MultiIndex DataFrame by specifying a range of values for one level.
  • Write a Pandas program to use pd.IndexSlice to slice data from a MultiIndex DataFrame for a specific level combination.
  • Write a Pandas program to extract rows using slicing on a MultiIndex and then compute the sum over a particular column.
  • Write a Pandas program to slice a MultiIndex DataFrame and then reset the index of the sliced result.

Python-Pandas Code Editor:

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

Previous: Set MultiIndex and access data in Pandas DataFrame.
Next: Swap MultiIndex Levels in Pandas DataFrame.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.