💡 Understanding Boolean Masking in Pandas
In Pandas, when you run a conditional check on a column (e.g., `df['Age'] > 30`), Python does not return a filtered dataset immediately. Instead, it generates a **Boolean Mask**—a Series of `True` and `False` values corresponding to every row. Passing this mask back into the DataFrame (`df[mask]`) filters the data instantly. You can combine multiple conditions using bitwise operators (`&` for AND, `|` for OR, `~` for NOT).
1. Single Condition Filtering (Greater Than)
Filtering an e-commerce customer dataset to isolate accounts with account balances exceeding $500.
Python (single_condition.py)
import pandas as pd
def filter_high_balance():
data = {
'Customer': ['Alice', 'Bob', 'Charlie', 'Diana', 'Evan'],
'Balance': [150.50, 750.25, 420.00, 1200.00, 310.80]
}
df = pd.DataFrame(data)
# Boolean mask & filtering
mask = df['Balance'] > 500
filtered_df = df[mask]
print("--- Customers with Balance > $500 ---")
print(filtered_df.to_string(index=False))
filter_high_balance()
Output:
--- Customers with Balance > $500 ---
Customer Balance
Bob 750.25
Diana 1200.00
2. Multiple Conditions with AND Operator (&)
Isolating software engineering staff earning a salary above $100k using the bitwise AND (`&`) operator. Note: parentheses around each condition are mandatory in Pandas.
Python (and_operator.py)
import pandas as pd
def filter_senior_engineers():
data = {
'Name': ['John', 'Emma', 'Liam', 'Olivia', 'Noah'],
'Department': ['Engineering', 'Marketing', 'Engineering', 'HR', 'Engineering'],
'Salary': [95000, 110000, 130000, 85000, 105000]
}
df = pd.DataFrame(data)
# Both conditions must be met (Parentheses required around each condition)
mask = (df['Department'] == 'Engineering') & (df['Salary'] >= 100000)
result = df[mask]
print("--- Senior Engineering Staff ---")
print(result.to_string(index=False))
filter_senior_engineers()
Output:
--- Senior Engineering Staff ---
Name Department Salary
Liam Engineering 130000
Noah Engineering 105000
3. Multiple Conditions with OR Operator (|)
Filtering a product inventory to find items belonging to either the 'Electronics' OR 'Apparel' category using the bitwise OR (`|`) operator.
Python (or_operator.py)
import pandas as pd
def filter_categories():
data = {
'Product': ['Laptop', 'Desk', 'Jacket', 'Headphones', 'Coffee Maker'],
'Category': ['Electronics', 'Furniture', 'Apparel', 'Electronics', 'Appliances'],
'Price': [1200, 250, 80, 150, 90]
}
df = pd.DataFrame(data)
mask = (df['Category'] == 'Electronics') | (df['Category'] == 'Apparel')
result = df[mask]
print("--- Electronics or Apparel Items ---")
print(result.to_string(index=False))
filter_categories()
Output:
--- Electronics or Apparel Items ---
Product Category Price
Laptop Electronics 1200
Jacket Apparel 80
Headphones Electronics 150
4. Inversion / NOT Operator (~)
Inverting a boolean mask using the tilde (`~`) operator to find all customers who have *not* churned.
Python (not_operator.py)
import pandas as pd
def filter_active_customers():
data = {
'Customer': ['Sam', 'Grace', 'Alex', 'Taylor', 'Jordan'],
'Is_Churned': [False, True, False, True, False]
}
df = pd.DataFrame(data)
# ~ operator negates the condition (finds NOT churned)
active_customers = df[~df['Is_Churned']]
print("--- Active Customers ---")
print(active_customers.to_string(index=False))
filter_active_customers()
Output:
--- Active Customers ---
Customer Is_Churned
Sam False
Alex False
Jordan False
5. Filtering with `.isin()` Method
Checking if column values exist within a specified list of targets, replacing tedious chains of `|` operators.
Python (isin_filter.py)
import pandas as pd
def filter_cities():
data = {
'Client': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6'],
'City': ['New York', 'London', 'Paris', 'Tokyo', 'Berlin', 'London']
}
df = pd.DataFrame(data)
target_cities = ['London', 'Paris', 'Tokyo']
result = df[df['City'].isin(target_cities)]
print("--- Clients in Target Cities ---")
print(result.to_string(index=False))
filter_cities()
Output:
--- Clients in Target Cities ---
Client City
C2 London
C3 Paris
C4 Tokyo
C6 London
6. Filtering Numeric Ranges with `.between()`
Extracting records where numerical values fall inclusively between a specified lower and upper bound.
Python (between_filter.py)
import pandas as pd
def filter_price_range():
data = {
'Item': ['Book', 'Shoes', 'Watch', 'Phone', 'Backpack'],
'Price': [25, 95, 250, 850, 60]
}
df = pd.DataFrame(data)
# Items priced between $50 and $300 inclusive
result = df[df['Price'].between(50, 300)]
print("--- Mid-Range Items ($50 - $300) ---")
print(result.to_string(index=False))
filter_price_range()
Output:
--- Mid-Range Items ($50 - $300) ---
Item Price
Shoes 95
Watch 250
Backpack 60
7. Handling Missing Values (`isna()` / `notna()`)
Filtering rows where essential tracking data is missing (`NaN`) or fully populated.
Python (missing_filter.py)
import pandas as pd
import numpy as np
def filter_missing_records():
data = {
'Order_ID': [101, 102, 103, 104, 105],
'Tracking_Number': ['TRK-99', np.nan, 'TRK-42', np.nan, 'TRK-11']
}
df = pd.DataFrame(data)
# Find orders missing tracking numbers
missing = df[df['Tracking_Number'].isna()]
print("--- Orders Missing Tracking Numbers ---")
print(missing.to_string(index=False))
filter_missing_records()
Output:
--- Orders Missing Tracking Numbers ---
Order_ID Tracking_Number
102 NaN
104 NaN
8. String Pattern Filtering using `.str.contains()`
Filtering text columns to find records containing specific keywords or substrings (case-insensitive).
Python (string_filter.py)
import pandas as pd
def filter_text_pattern():
data = {
'Email': ['alice@gmail.com', 'bob@yahoo.com', 'charlie@gmail.com', 'diana@outlook.com']
}
df = pd.DataFrame(data)
# Filter users with gmail accounts
gmail_users = df[df['Email'].str.contains('gmail.com', case=False, na=False)]
print("--- Gmail Users ---")
print(gmail_users.to_string(index=False))
filter_text_pattern()
Output:
--- Gmail Users ---
Email
alice@gmail.com
charlie@gmail.com
9. SQL-like Filtering using `.query()`
Using Pandas `.query()` method to write cleaner, SQL-style expression strings for complex boolean filters.
Python (query_filter.py)
import pandas as pd
def query_dataset():
data = {
'Product': ['Mouse', 'Keyboard', 'Monitor', 'Printer', 'Webcam'],
'Price': [25, 75, 300, 150, 60],
'Stock': [100, 4, 12, 0, 50]
}
df = pd.DataFrame(data)
# Query expression: Price > 50 AND Stock > 0
result = df.query("Price > 50 and Stock > 0")
print("--- Available Premium Products ---")
print(result.to_string(index=False))
query_dataset()
Output:
--- Available Premium Products ---
Product Price Stock
Keyboard 75 4
Monitor 300 12
Webcam 60 50
10. Conditional Value Updating & Filtering Combined
Locating specific rows with boolean masks and updating their column values conditionally in place.
Python (conditional_update.py)
import pandas as pd
def conditional_update():
data = {
'Student': ['Alice', 'Bob', 'Charlie', 'Diana'],
'Score': [42, 85, 39, 92]
}
df = pd.DataFrame(data)
# Mark failing scores (< 50) as 'Retake' in a new Status column
df['Status'] = 'Pass'
df.loc[df['Score'] < 50, 'Status'] = 'Retake'
print("--- Updated Student Status ---")
print(df.to_string(index=False))
conditional_update()
Output:
--- Updated Student Status ---
Student Score Status
Alice 42 Retake
Bob 85 Pass
Charlie 39 Retake
Diana 92 Pass