++++Data Science
May 2026×Notebook lesson
Notebook converted from Jupyter for blog publishing.
02-Conditional-Filtering
Driptanil DattaSoftware Developer
Conditional Filtering
Imports
import numpy as np
import pandas as pddf = pd.read_csv('tips.csv')df.head()HTML
MORE
total_bill
tip
sex
smoker
dayConditions
# df['total_bill'] > 30bool_series = df['total_bill'] > 30df[bool_series]HTML
MORE
total_bill
tip
sex
smoker
daydf[df['total_bill']>30]HTML
MORE
total_bill
tip
sex
smoker
daydf[df['sex'] == 'Male']HTML
MORE
total_bill
tip
sex
smoker
dayMultiple Conditions
Recall the steps:
- Get the conditions
- Wrap each condition in parenthesis
- Use the | or & operator, depending if you want an
- OR | (either condition is True)
- AND & (both conditions must be True)
- You can also use the ~ operator as a NOT operation
df[(df['total_bill'] > 30) & (df['sex']=='Male')]HTML
MORE
total_bill
tip
sex
smoker
daydf[(df['total_bill'] > 30) & ~(df['sex']=='Male')]HTML
MORE
total_bill
tip
sex
smoker
daydf[(df['total_bill'] > 30) & (df['sex']!='Male')]HTML
MORE
total_bill
tip
sex
smoker
day# The Weekend
df[(df['day'] =='Sun') | (df['day']=='Sat')]HTML
MORE
total_bill
tip
sex
smoker
dayConditional Operator isin()
We can use .isin() operator to filter by a list of options.
options = ['Sat','Sun']
df['day'].isin(options)RESULT
MORE
0 True
1 True
2 True
3 True
4 Truedf[df['day'].isin(['Sat','Sun'])]HTML
MORE
total_bill
tip
sex
smoker
day