Boolean indexing in Pandas DataFrame
8. Boolean Indexing: Column 'x' > 6
Write a Pandas program to use Boolean indexing to select rows where column 'x' > 6.
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]
})
# Boolean indexing to select rows
result = df[df['X'] > 6]
print(result)
Output:
X Y 2 8 9 4 7 1
Explanation:
- Import pandas library.
- Create a DataFrame.
- Apply Boolean indexing to select rows where column 'X' > 6.
- Print the results.
For more Practice: Solve these Related Problems:
- Write a Pandas program to filter rows where column 'x' is greater than 6 using boolean indexing and display the result.
- Write a Pandas program to apply a boolean condition on column 'x' to extract rows with values exceeding 6 and then sort by another column.
- Write a Pandas program to create a boolean mask for rows where 'x' > 6 and use it to compute summary statistics on the filtered DataFrame.
- Write a Pandas program to use boolean indexing to select rows where 'x' is greater than 6 and then plot these rows against another variable.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Indexing with .loc in Pandas DataFrame.
Next: Selecting rows by position in Pandas DataFrame.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.