How to Select Rows Where Column Equals Value in pandas
To select rows where a column equals a value in pandas, use
df[df['column_name'] == value]. This filters the DataFrame and returns only rows matching the condition.Syntax
The basic syntax to select rows where a column equals a value is:
df: your pandas DataFramedf['column_name'] == value: condition to check equality- Using
df[condition]returns rows where the condition is True
python
filtered_df = df[df['column_name'] == value]Example
This example shows how to select rows where the 'Age' column equals 30 from a sample DataFrame.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 35, 30], 'City': ['NY', 'LA', 'Chicago', 'Houston']} df = pd.DataFrame(data) filtered_df = df[df['Age'] == 30] print(filtered_df)
Output
Name Age City
1 Bob 30 LA
3 David 30 Houston
Common Pitfalls
Common mistakes include:
- Using a single equals sign
=instead of double equals==for comparison. - Not using quotes around the column name in
df['column_name']. - Trying to use
df.column_name == valuewhen the column name has spaces or special characters.
python
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) # Wrong: single equals sign (syntax error) # filtered_df = df[df['Age'] = 30] # Wrong: no quotes around column name (raises KeyError) # filtered_df = df[df['Age'] == 30] # Correct way filtered_df = df[df['Age'] == 30] print(filtered_df)
Output
Name Age
1 Bob 30
Quick Reference
Summary tips for selecting rows where a column equals a value:
- Use
df[df['column_name'] == value]to filter rows. - Ensure the column name is a string inside brackets and quotes.
- Use
==for comparison, not=. - For multiple conditions, combine with
&and parentheses.
Key Takeaways
Use df[df['column_name'] == value] to select rows where a column matches a value.
Always use double equals (==) for comparison, not a single equals (=).
Put the column name in quotes inside square brackets: df['column_name'].
This method returns a filtered DataFrame with only matching rows.
For complex filters, combine conditions with & and parentheses.