Introduction
We select rows by condition to find and work with only the data that matters to us.
We select rows by condition to find and work with only the data that matters to us.
filtered_df = df[df['column_name'] <condition> value]filtered_df = df[df['age'] > 30]
filtered_df = df[df['city'] == 'New York']
filtered_df = df[(df['score'] >= 80) & (df['passed'] == True)]
filtered_df = df[df['name'].str.contains('John')]
This code creates a small table of people with their ages and cities. Then it selects only those people older than 30 and prints them.
import pandas as pd data = {'name': ['Alice', 'Bob', 'Charlie', 'David'], 'age': [25, 35, 30, 40], 'city': ['New York', 'Los Angeles', 'New York', 'Chicago']} df = pd.DataFrame(data) # Select rows where age is greater than 30 filtered_df = df[df['age'] > 30] print(filtered_df)
Use & for AND and | for OR when combining multiple conditions. Remember to put each condition in parentheses.
String conditions can use methods like str.contains() for partial matches.
Filtering does not change the original data unless you assign it back.
Use square brackets with a condition to select rows.
Conditions return True or False for each row to keep or drop it.
You can combine multiple conditions with & (and) or | (or).
df[df['age'] > 30] do in pandas?df['age'] > 30 creates a True/False mask for each row based on the 'age' value.df[condition] returns only rows where the condition is True, i.e., 'age' > 30.==, not single = or triple ===.df['score'] is correct and safe for all column names.import pandas as pd
data = {'name': ['Ann', 'Bob', 'Cara', 'Dan'], 'age': [25, 35, 30, 40]}
df = pd.DataFrame(data)
What is the output of df[df['age'] >= 30]?df[df['score'] > 50 && df['age'] < 30]
& for 'and', not double ampersand &&.df[(df['score'] > 50) & (df['age'] < 30)] with parentheses and single &.df with columns 'city', 'temperature', and 'humidity'. How do you select rows where the city is 'Paris' and temperature is above 20 or humidity is below 30?df[(df['city'] == 'Paris') & ((df['temperature'] > 20) | (df['humidity'] < 30))]Pass the test and this pattern moves unknown