w3resource

Boolean indexing in Pandas DataFrame


Pandas: Advanced Indexing and Slicing Exercise-8 with Solution


Boolean Indexing:

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.

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.



Follow us on Facebook and Twitter for latest update.