Conditional selection with .loc in Pandas DataFrame
10. .loc Row Selection Based on Condition
Write a Pandas program to use .loc to select rows based on a condition.
Sample Solution :
Python Code :
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'P': [1, 6, 8, 3, 7],
'Q': [5, 2, 9, 4, 1]
})
# Conditional selection using .loc
result = df.loc[df['P'] > 3]
print(result)
Output:
P Q 1 6 2 2 8 9 4 7 1
Explanation:
- Import pandas library.
- Create a DataFrame.
- Use .loc to select rows where column 'P' > 3.
- Print the results.
For more Practice: Solve these Related Problems:
- Write a Pandas program to use .loc to select rows that satisfy a specified condition from a DataFrame.
- Write a Pandas program to apply .loc with a conditional expression to filter rows and display selected columns.
- Write a Pandas program to use .loc to select rows where a particular column meets a condition and then update another column’s values.
- Write a Pandas program to combine .loc and boolean conditions to extract rows and then compute aggregated metrics.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Selecting rows by position in Pandas DataFrame.
Next: Setting values with .loc in Pandas DataFrame.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.