Python tutoring online
Home

How to Filter a Pandas DataFrame Using Conditions

Filtering a Pandas DataFrame means keeping only the rows that meet a condition. For example, you might want to find employees in the IT department, customers who spent more than £100, or products with low stock. Pandas makes this possible with Boolean conditions, comparison operators and a technique called Boolean indexing.

This guide explains how to filter rows in a DataFrame, combine multiple conditions, match values from a list, filter numeric ranges and text, and use query(). Examples use a small employee dataset that you can run in Python or a Jupyter Notebook.

If you are new to table structures, start with the Pandas DataFrame tutorial. For selecting columns and individual rows, see how to select rows and columns in Pandas.

Learn Pandas with Practical Guidance

If you need help with Python, Pandas, data analysis coursework or a project, one-to-one tutoring can help you practise filtering, cleaning and analysing real datasets.

Get 1-on-1 Python Tutoring

1. Create a Sample Pandas DataFrame

Run this setup code first. It creates employee records with department, age, salary and city columns.

Python
import pandas as pd

employees = pd.DataFrame({
    "Name": ["Amina", "Bilal", "Chen", "Dina", "Ethan", "Fatima"],
    "Department": ["IT", "Sales", "IT", "HR", "Sales", "IT"],
    "Age": [28, 35, 31, 26, 42, 29],
    "Salary": [72000, 65000, 81000, 59000, 88000, 76000],
    "City": ["London", "Leeds", "London", "Bristol", "Leeds", "Manchester"]
})

print(employees)
     Name Department  Age  Salary        City
0   Amina         IT   28   72000      London
1   Bilal      Sales   35   65000       Leeds
2    Chen         IT   31   81000      London
3    Dina         HR   26   59000     Bristol
4   Ethan      Sales   42   88000       Leeds
5  Fatima         IT   29   76000  Manchester

Filtering returns the rows that satisfy a test. Unless you explicitly assign the result back to employees, the original DataFrame remains unchanged.

2. Filter a DataFrame with One Condition

To select employees whose salary is greater than 70,000, place a comparison inside square brackets:

Python
high_salary = employees[employees["Salary"] > 70000]
print(high_salary)
     Name Department  Age  Salary        City
0   Amina         IT   28   72000      London
2    Chen         IT   31   81000      London
4   Ethan      Sales   42   88000       Leeds
5  Fatima         IT   29   76000  Manchester

The expression employees["Salary"] > 70000 creates a Boolean Series containing True or False for each row. Pandas keeps the rows where the result is True.

Filter using equality

Python
it_employees = employees[employees["Department"] == "IT"]
print(it_employees[["Name", "Department", "Salary"]])
     Name Department  Salary
0   Amina         IT   72000
2    Chen         IT   81000
5  Fatima         IT   76000

Text comparisons are case-sensitive. If the values in the column are "IT", comparing them with "it" will not match those records.

3. Pandas Filtering Operators

OperatorMeaningExample
==Equal todf["City"] == "Leeds"
!=Not equal todf["Department"] != "HR"
>Greater thandf["Age"] > 30
>=Greater than or equal todf["Salary"] >= 75000
<Less thandf["Age"] < 30
<=Less than or equal todf["Salary"] <= 65000

For example, find employees aged 30 or younger:

Python
young_employees = employees[employees["Age"] <= 30]
print(young_employees[["Name", "Age"]])
     Name  Age
0   Amina   28
3    Dina   26
5  Fatima   29

4. Filter with Multiple Conditions

Combine conditions to answer more specific questions. In Pandas, use & for AND and | for OR. Put parentheses around each comparison.

AND: both conditions must be true

Find IT employees whose salary is at least 75,000:

Python
result = employees[(employees["Department"] == "IT") & (employees["Salary"] >= 75000)]
print(result[["Name", "Department", "Salary"]])
     Name Department  Salary
2    Chen         IT   81000
5  Fatima         IT   76000

OR: either condition can be true

Find employees who work in HR or Sales:

Python
result = employees[(employees["Department"] == "HR") | (employees["Department"] == "Sales")]
print(result[["Name", "Department"]])
    Name Department
1  Bilal      Sales
3   Dina         HR
4  Ethan      Sales

NOT: exclude a condition

Python
not_sales = employees[~(employees["Department"] == "Sales")]
print(not_sales[["Name", "Department"]])

The tilde (~) reverses a Boolean condition. Here it selects rows where the department is not Sales.

Important: Do not use Python's and and or between Pandas Series conditions. Use & and |, with parentheses around each comparison.

5. Filter Rows with isin()

Use isin() when a column should match any value from a list. This is more concise than writing many OR conditions.

Python
selected = employees[employees["City"].isin(["London", "Leeds"])]
print(selected[["Name", "City"]])
    Name    City
0  Amina  London
1  Bilal   Leeds
2   Chen  London
4  Ethan   Leeds

To exclude those cities, negate the result:

Python
other_cities = employees[~employees["City"].isin(["London", "Leeds"])]

This is useful when filtering categories such as regions, product types, job titles or customer segments.

6. Filter a Numeric Range with between()

The between() method checks whether values fall within a range. By default, both endpoints are included.

Python
age_range = employees[employees["Age"].between(28, 35)]
print(age_range[["Name", "Age"]])
     Name  Age
0   Amina   28
1   Bilal   35
2    Chen   31
5  Fatima   29

This example includes ages 28 and 35. To exclude an endpoint, set the inclusive argument appropriately, for example between(28, 35, inclusive="neither") to exclude both endpoints.

7. Filter Text with str Methods

Pandas provides string methods through the .str accessor. For example, contains() finds values containing a substring.

Find text that contains a word

Python
london_rows = employees[employees["City"].str.contains("lon", case=False, na=False)]
print(london_rows[["Name", "City"]])

case=False makes the search case-insensitive. na=False treats missing values as non-matches rather than returning them in the filter mask.

Match text at the beginning or end

Python
starts_with_m = employees[employees["City"].str.startswith("M")]
ends_with_s = employees[employees["City"].str.endswith("s")]

Other useful string methods include str.lower(), str.upper(), str.startswith() and str.endswith(). If a text column may contain missing values, use a suitable na option or clean the data first.

8. Filter Missing Values

Missing values need special handling because comparisons with missing data do not behave like ordinary equality tests. Use isna() to find missing values and notna() to keep non-missing values.

Python
data = pd.DataFrame({
    "Name": ["Amina", "Bilal", "Chen", "Dina"],
    "Score": [88, None, 91, None]
})

missing_scores = data[data["Score"].isna()]
known_scores = data[data["Score"].notna()]
print(missing_scores)
print(known_scores)

For a wider discussion of handling missing values, see the Pandas missing values tutorial.

9. Filter with query()

The query() method lets you write many filters as a readable expression string. It can be convenient when column names are simple identifiers.

Python
result = employees.query("Age >= 30 and Salary > 70000")
print(result[["Name", "Age", "Salary"]])

You can also refer to a Python variable by prefixing its name with @:

Python
minimum_salary = 75000
result = employees.query("Salary >= @minimum_salary")

query() is an alternative to Boolean indexing, not a requirement. For complex expressions or column names containing spaces, review the syntax carefully; ordinary bracket filtering is often the clearest choice.

10. Keep or Reset the Index After Filtering

Filtering generally preserves the original index labels, so the result may have gaps in its index. This is normal and does not mean rows are missing accidentally.

Python
high_salary = employees[employees["Salary"] > 70000]
reset_result = high_salary.reset_index(drop=True)
print(reset_result)

Use reset_index(drop=True) when you want a fresh sequence of index values from zero. Without drop=True, the old index is added as a column.

11. Common Pandas Filtering Mistakes

MistakeCorrect approachReason
df["Age"] > 30 and df["Salary"] > 70000(df["Age"] > 30) & (df["Salary"] > 70000)Series conditions need element-wise operators.
df[df["City"] = "Leeds"]df[df["City"] == "Leeds"]Use equality comparison, ==, not assignment.
df[df["Department"] == "it"]Match the stored case or normalise text first.Text comparisons are case-sensitive.
Forgetting parentheses in combined conditions(condition_a) & (condition_b)Parentheses make operator precedence clear and prevent errors.
Expecting filtered index labels to restart at zeroUse reset_index(drop=True) if required.Filtering retains the original row labels.

12. Practice Exercises

Use the employees DataFrame from the beginning of this tutorial. Try each task before opening the solutions.

  1. Find employees who live in Leeds.
  2. Find employees with a salary greater than or equal to 75,000.
  3. Find employees in IT who are younger than 30.
  4. Find employees who live in London or Manchester.
  5. Find employees aged from 30 to 40, including both endpoints.
  6. Use query() to find employees whose salary is below 70,000.
Show solutions
Python
employees[employees["City"] == "Leeds"]
employees[employees["Salary"] >= 75000]
employees[(employees["Department"] == "IT") & (employees["Age"] < 30)]
employees[employees["City"].isin(["London", "Manchester"])]
employees[employees["Age"].between(30, 40)]
employees.query("Salary < 70000")

13. Frequently Asked Questions

How do I filter a DataFrame in Pandas?

Use Boolean indexing, such as df[df["Age"] > 30]. Pandas returns only the rows where the condition is true.

How do I filter a Pandas DataFrame by two conditions?

Put each condition in parentheses and combine them with & for AND or | for OR. For example, df[(df["Age"] > 30) & (df["City"] == "Leeds")].

What is the difference between loc and filtering?

.loc selects data by row and column labels and can also accept a Boolean condition. Boolean indexing, such as df[df["Age"] > 30], is a direct way to filter rows by a condition.

How do I filter rows that match several values?

Use isin(), for example df[df["City"].isin(["London", "Leeds"])].

Can I filter a DataFrame using text?

Yes. Use string methods such as df["Name"].str.contains("an", case=False, na=False) to match text in a column.

Does filtering change the original DataFrame?

Creating a filtered result in a new variable does not replace the original DataFrame. To keep the filtered rows in the original variable, assign the result back, for example df = df[df["Age"] > 30].

Continue Learning Pandas

Filtering is often followed by sorting, grouping or cleaning the selected records. Continue with these related lessons:

Need Help with Pandas or Data Analysis?

Get support with DataFrames, filtering, data cleaning, Python programming or a data-analysis assignment through one-to-one online tutoring.

Explore Python Tutoring



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net