Lesson 20 · Mastering Pandas
Master Filtering Rows and Columns in Pandas Using Query and isin for Data Analysis
Welcome! Today we will learn intermediate techniques for slicing and dicing data in pandas. We will use the restaurant Tips dataset to explore how to filter…
- CourseMastering Pandas
- Lesson20 of 44
- Video17 min
- FormatJupyter notebook · 15 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbFiltering Rows and Columns in Pandas: Query and isin#
Welcome! Today we will learn intermediate techniques for slicing and dicing data in pandas.
We will use the restaurant Tips dataset to explore how to filter rows and columns using the query() method and the isin() function.
Let us get started!
import warnings
warnings.filterwarnings("ignore")
# Data setup (Restaurant Tips Dataset)
import seaborn as sns
import numpy as np
np.random.seed(42)
df = sns.load_dataset('tips')
print(df.shape)
print(df.head(3))
Sneak peek at the columns#
Notice our dataset contains columns like: total_bill, tip, sex, smoker, day, time, and size.
We will practice filtering using these!
# Checking column names
print(df.columns.tolist())
# Basic filtering using boolean indexing
high_tips = df[df['tip'] > 5]
print(high_tips.head(2))
Using query() for readable filtering#
The query() method lets us filter with expressions closer to how we would write them in math or SQL.
Let us try it out!
# Filtering with query: tips greater than five
query_result = df.query('tip > 5')
print(query_result.head(2))
# Filtering multiple conditions
dinner_high_tip = df.query('time == "Dinner" and tip > 5')
print(dinner_high_tip.head(2))
Why use query?#
Query can be easier to read, especially with long conditions.
It avoids a lot of code clutter with brackets and ampersands (&).
# Filtering with variables in query (using @ syntax)
my_limit = 4.5
filtered = df.query('tip > @my_limit and smoker == "No"')
print(filtered.head(2))
# Query for multiple values: Use in and not in
selected_days = ['Sat', 'Sun']
weekends = df.query('day in @selected_days')
print(weekends['day'].value_counts())
# The isin() function: filter with lists or sets
weekend_rows = df[df['day'].isin(['Sat', 'Sun'])]
print(weekend_rows.sample(3, random_state=42))
# Negate with ~ : NOT in the list
not_weekend = df[~df['day'].isin(['Sat', 'Sun'])]
print(not_weekend['day'].unique())
# Select a subset of columns by filtering column names
cols = ['total_bill', 'tip', 'day']
bills = df[cols]
print(bills.head())
# Combining row and column filtering
lunch_bills = df.query('time == "Lunch"')[['total_bill', 'tip', 'sex']]
print(lunch_bills.head())
Practice: Filter diners#
Try using query() to select all dinners (Dinner time) where the party size was three or more.
Practice makes perfect!
# Chaining: Filter + sort
big_tip_sorted = df.query('tip >= 5').sort_values('total_bill', ascending=False)
print(big_tip_sorted[['total_bill', 'tip']].head())
# Find all unique values a column takes
print(df['day'].unique())
# User input: filter by day (case-sensitive)
user_day = input("Type a day (Thur, Fri, Sat, Sun): ")
print(df[df['day'] == user_day].head())
# Quick summary: group by day, mean tip
print(df.groupby('day')['tip'].mean().round(2))
Recap: Filtering with query and isin#
We practiced filtering rows with readable, powerful tools. Query() allows us to write filter expressions like math or SQL. Isin() checks column values against lists or sets. Both make slicing our DataFrame easier.
Remember: practice and experimenting help you master filtering!
What's next?#
Ready to build more skills? Try combining filters with visualization or aggregation!
Watch our next video for advanced pandas tricks and follow along. Happy learning!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



