w3resource

Advanced Boolean indexing in Pandas DataFrame

Pandas: Advanced Indexing and Slicing Exercise-13 with Solution

Advanced Boolean Indexing:

Write a Pandas program to select rows where column 'X' > 5 and column 'Y' < 5.

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

# Advanced Boolean indexing
result = df[(df['X'] > 5) & (df['Y'] < 5)]
print(result)

Output:

   X  Y
1  6  2
4  7  1

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Apply advanced Boolean indexing to select rows where column 'X' > 5 and column 'Y' < 5.
  • Print the results.

Python-Pandas Code Editor:

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

Previous: Slicing DataFrame with .loc in Pandas.
Next: 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/advanced-boolean-indexing-in-pandas-dataframe.php