Pandas MultiIndex slicing with loc
14. .loc Slicing of a MultiIndex DataFrame
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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to use .loc to slice a MultiIndex DataFrame based on specific index level values.
- Write a Pandas program to extract a subset from a MultiIndex DataFrame using .loc with a partial index key.
- Write a Pandas program to slice data from a MultiIndex DataFrame and then reset its index.
- Write a Pandas program to use .loc to filter a MultiIndex DataFrame and compute a summary statistic on the sliced data.
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.