Slice DataFrame with MultiIndex in Pandas
Pandas: Advanced Indexing and Slicing Exercise-4 with Solution
Slice DataFrame with MultiIndex:
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.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics