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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics