Select rows with specific condition in Pandas DataFrame
1. Select Rows Based on Column 'A' Value
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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to select rows where the value in the 'A' column is greater than 4 and display only the first five matching rows.
- Write a Pandas program to filter rows from a DataFrame where column 'A' exceeds 4 and then sort the results by another column.
- Write a Pandas program to select rows with 'A' > 4 and then compute the mean of the remaining columns.
- Write a Pandas program to extract rows where 'A' is greater than 4 and create a new DataFrame with only these rows.
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.