0
0
Pandasdata~5 mins

Multiple conditions with & and | in Pandas

Choose your learning style9 modes available
Introduction

We use multiple conditions to filter data based on more than one rule at the same time. This helps us find exactly the rows we want.

You want to find people who are older than 30 and live in a specific city.
You want to select products that are either on sale or have a high rating.
You want to filter data where temperature is above 20 degrees and humidity is below 50%.
You want to get rows where a score is less than 50 or the status is 'failed'.
Syntax
Pandas
df[(condition1) & (condition2)]  # for AND

df[(condition1) | (condition2)]  # for OR

Use parentheses around each condition to avoid errors.

Use & for AND, and | for OR between conditions.

Examples
Select rows where age is more than 30 AND city is New York.
Pandas
df[(df['age'] > 30) & (df['city'] == 'New York')]
Select rows where price is less than 100 OR rating is more than 4.
Pandas
df[(df['price'] < 100) | (df['rating'] > 4)]
Select rows where temperature is above 20 AND humidity is below 50.
Pandas
df[(df['temperature'] > 20) & (df['humidity'] < 50)]
Sample Program

This code creates a small table of people with their age, city, and score. Then it shows how to filter rows using AND and OR conditions.

Pandas
import pandas as pd

# Create sample data
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
    'age': [25, 35, 30, 40, 22],
    'city': ['New York', 'Los Angeles', 'New York', 'Chicago', 'Los Angeles'],
    'score': [85, 90, 70, 60, 95]
}

df = pd.DataFrame(data)

# Filter: age > 30 AND city is Los Angeles
filtered_and = df[(df['age'] > 30) & (df['city'] == 'Los Angeles')]

# Filter: score < 70 OR city is Chicago
filtered_or = df[(df['score'] < 70) | (df['city'] == 'Chicago')]

print('Rows with age > 30 AND city = Los Angeles:')
print(filtered_and)
print('\nRows with score < 70 OR city = Chicago:')
print(filtered_or)
OutputSuccess
Important Notes

Always put each condition inside parentheses when combining with & or |.

Use & for AND, | for OR, not the words 'and' or 'or'.

Make sure your DataFrame columns exist to avoid errors.

Summary

Use & to combine conditions that must all be true (AND).

Use | to combine conditions where any can be true (OR).

Always wrap each condition in parentheses to avoid mistakes.