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.
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.