w3resource

Advanced Boolean indexing in Pandas DataFrame


13. Boolean Indexing: Conditions on 'X' and 'Y'

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to select rows where column 'X' > 5 and column 'Y' < 5 using a combined condition.
  • Write a Pandas program to filter a DataFrame with multiple conditions on 'X' and 'Y' and then display the resulting subset.
  • Write a Pandas program to use boolean indexing to extract rows that satisfy conditions on two columns and compute the mean of another column.
  • Write a Pandas program to combine conditions on 'X' and 'Y' using & operator and then visualize the filtered data.

Go to:


PREV : .loc Slicing Based on Row and Column Labels.
NEXT : .loc Slicing of a MultiIndex DataFrame.

Python-Pandas Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.