Labs ICT
Pro Login

Conditional Selection

Filtering rows with conditions.

Conditional Selection

Let me show you how to filter data based on conditions. This is where Pandas really starts to feel powerful — like having a super-smart filter for your spreadsheet.

Basic Conditions

Start with simple comparisons:


import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
        'Age': [25, 30, 35, 28],
        'Score': [88, 92, 79, 95]}
df = pd.DataFrame(data)

print(df[df['Age'] > 28])
    

Simple as that. The condition `df['Age'] > 28` creates a True/False mask, and Pandas returns only the rows where it's True.

Multiple Conditions

Need to filter on more than one condition? Use `&` (AND) or `|` (OR):


print(df[(df['Age'] > 25) & (df['Score'] > 85)])
    

The parentheses are mandatory. Trust me, forget them and you'll get a cryptic error. I definitely did when I started.

isin() and between()

Two handy shortcuts for common patterns:


print(df[df['Name'].isin(['Alice', 'Diana'])])

print(df[df['Age'].between(25, 30)])
    

`isin()` checks if values are in a list. `between()` checks if values fall within a range. These are way cleaner than writing multiple OR conditions.

Try it Yourself →

Key Takeaways

  • Use comparison operators to create boolean masks
  • Combine conditions with `&` (AND) and `|` (OR)
  • Always wrap conditions in parentheses
  • `isin()` and `between()` are clean shortcuts for common filters