w3resource

Pandas - Conditional Selection with MultiIndex

Pandas: Advanced Indexing and Slicing Exercise-15 with Solution

Conditional Selection with MultiIndex:

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.

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.



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://198.211.115.131/python-exercises/pandas/pandas-conditional-selection-with-multiindex.php