Pandas - Conditional Selection with MultiIndex
15. MultiIndex Conditional Data Selection
Write a Pandas program that uses MultiIndex to select data based on conditions.
Sample Solution :
Python Code :
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'X': [1, 6, 8, 3, 7],
'Y': [5, 2, 9, 4, 1],
'Z': ['one', 'one', 'two', 'two', 'one']
})
# Set MultiIndex
df = df.set_index(['Z', 'X'])
# Conditional selection with MultiIndex
result = df.loc[('one', slice(None))]
print(result)
Output:
Y X 1 5 6 2 7 1
Explanation:
- Import pandas library.
- Create a DataFrame.
- Set a MultiIndex using columns 'Z' and 'X'.
- Use .loc with a slice to select data for MultiIndex 'one'.
- Print the results.
For more Practice: Solve these Related Problems:
- Write a Pandas program to create a MultiIndex DataFrame and then use conditional selection to filter data based on level values.
- Write a Pandas program to apply boolean conditions on a MultiIndex DataFrame and return rows that meet specific criteria.
- Write a Pandas program to select data from a MultiIndex DataFrame using a combination of index levels and column conditions.
- Write a Pandas program to create a MultiIndex DataFrame, apply a custom filter to each level, and display the filtered result.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Pandas MultiIndex slicing with loc.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.