Filtering

Pandas Basics

1 min read

Published Sep 29 2025, updated Aug 17 2026


21
0
0
0

PandasPython

Filtering means selecting rows based on conditions applied to columns.


Sample data:

import pandas as pddf = pd.DataFrame({    "Name": ["Alice", "Bob", "Charlie", "David"],    "Age": [25, 30, 35, 40],    "Salary": [50000, 60000, 75000, 80000]})



Single Condition

Using the boolean indexing, so what its actually passing in from the condition is the array of True/False values and only displaying the ones where the value equates to True.

# Filter rows where Age > 30filtered_df = df[df["Age"] > 30]print(filtered_df)

Output:

     Name  Age  Salary2  Charlie   35   750003    David   40   80000



Multiple Conditions (AND / OR)

  • AND: &
  • OR: |
  • Brackets required around each condition
# Age > 30 AND Salary > 70000df[(df["Age"] > 30) & (df["Salary"] > 70000)]# Age < 35 OR Salary < 60000df[(df["Age"] < 35) | (df["Salary"] < 60000)]



Using .query()

  • Cleaner syntax for filtering with column names directly.
df.query("Age > 30 & Salary > 70000")

Explanation:

  • Useful when you have multiple conditions.
  • You can use brackets to make more readable.
  • Use & for AND, | for OR, ~ for NOT.
  • Department == 'IT' : Department is IT.
  • Salary <= @max_salary : You can pass Python variables using the @ symbol, in this example the variable is max_salary.
  • Column names must be valid Python identifiers (no spaces, no punctuation).
    • Workaround: rename columns or use backticks: df.query("`Column Name` > 10")
  • Only for row filtering, not for column selection.




Filtering with .isin()

  • Select rows where a column value is in a list of values.
df[df["Name"].isin(["Alice", "David"])]

Output:

    Name  Age  Salary0  Alice   25   500003  David   40   80000



Filtering with string methods

# Names starting with 'C'df[df["Name"].str.startswith("C")]# Names containing 'a' (case-sensitive)df[df["Name"].str.contains("a")]



Resetting Index after Filtering

After filtering or sorting, the index may be non-sequential:

filtered_df = df[df["Age"] > 30].reset_index(drop=True)

drop=True removes the old index.

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact
Pandas Basics | Filtering | SimpleSteps.guide