Boolean indexing helps you pick rows or columns from data based on true or false conditions. It makes finding specific data easy and fast.
0
0
Boolean indexing in Pandas
Introduction
You want to find all sales above a certain amount in a sales report.
You need to select students who scored more than 80 in a test.
You want to filter out products that are out of stock from a list.
You want to see only the rows where temperature is below freezing.
You want to select customers from a specific city in your data.
Syntax
Pandas
filtered_data = data[condition]
data is your DataFrame.
condition is a boolean expression that returns True or False for each row.
Examples
Selects rows where the 'age' column is greater than 30.
Pandas
filtered = df[df['age'] > 30]
Selects rows where 'age' is 18 or less.
Pandas
young = df[df['age'] <= 18]
Selects rows where salary is above 50000 and department is 'Sales'.
Pandas
high_salary = df[(df['salary'] > 50000) & (df['department'] == 'Sales')]
Selects rows where 'in_stock' is False.
Pandas
not_in_stock = df[~(df['in_stock'])]Sample Program
This code creates a small table of employees. Then it picks only those who are older than 30 years and prints them.
Pandas
import pandas as pd data = { 'name': ['Alice', 'Bob', 'Charlie', 'David'], 'age': [25, 17, 35, 45], 'salary': [50000, 30000, 70000, 90000], 'department': ['HR', 'IT', 'Sales', 'Sales'] } df = pd.DataFrame(data) # Select employees older than 30 older_than_30 = df[df['age'] > 30] print(older_than_30)
OutputSuccess
Important Notes
Boolean indexing returns a new DataFrame with only the rows where the condition is True.
Use parentheses when combining multiple conditions with & (and) or | (or).
The ~ symbol means 'not' and flips True to False and vice versa.
Summary
Boolean indexing helps filter data easily using True/False conditions.
Use it to select rows that meet one or more conditions.
Remember to use parentheses when combining conditions.