Filtering with a Condition
A boolean mask filters rows by a condition. A mask is a Series of True and False, one value per row.
Build a mask
The comparison tests each row. Only Mug and Pen have more than 2 units.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Coffee", "Mug", "Pen"],
"category": ["Drink", "Drink", "Home", "Office"],
"units": [2, 1, 3, 5],
})
print(df["units"] > 2)Use the mask to filter
The mask inside brackets keeps the two True rows.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Coffee", "Mug", "Pen"],
"category": ["Drink", "Drink", "Home", "Office"],
"units": [2, 1, 3, 5],
})
print(df[df["units"] > 2])A text condition
The == test keeps rows where the category is Drink.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Coffee", "Mug", "Pen"],
"category": ["Drink", "Drink", "Home", "Office"],
"units": [2, 1, 3, 5],
})
print(df[df["category"] == "Drink"])Example
import io
import pandas as pd
SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
print(sales[sales["units"] >= 3])Key points
- A comparison like df["units"] > 2 builds a mask.
- True marks the rows that pass, and False marks the rows that fail.
- A DataFrame with a mask inside brackets keeps only the True rows.
- Text columns filter with ==, like df["category"] == "Drink".
- The mask itself is a Series, and the filtered result is a DataFrame.
In this example, the sales table is read from the CSV text. The mask sales["units"] >= 3 is True for rows with 3 or more units. The filtered table keeps those four rows.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does df[df["units"] > 2] return?