w3resource

Select rows with specific condition in Pandas DataFrame


Pandas: Advanced Indexing and Slicing Exercise-1 with Solution


Select Rows with Specific Condition:

Write a Pandas program to select rows where the value in the 'A' column is greater than 4.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'A': [1, 6, 8, 3, 7],
    'B': [5, 2, 9, 4, 1]
})

# Select rows where 'A' is greater than 4
result = df[df['A'] > 4]
print(result)

Output:

   A  B
1  6  2
2  8  9
4  7  1

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Select rows where column 'A' values are greater than 4.
  • Print the results.

Python-Pandas Code Editor:

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

Previous: Pandas Advanced Indexing and Slicing Exercises Home.
Next: Select specific columns 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.