Data Science ยท Chapter 10 of 43

Filtering & Sorting

Use BOOLEAN MASKS to filter rows and `sort_values` to reorder.

Combine filters with `&` (and) and `|` (or), and wrap each condition in parentheses.

Example 1 (python)
import pandas as pd
df = pd.read_csv('sales.csv')
recent = df[(df['year'] == 2025) & (df['amount'] > 1000)]

Multi-condition filter.

Example 2 (python)
print(df.sort_values('amount', ascending=False).head())

Sort by amount descending.

Key points

  • & / | for and/or with masks.
  • Wrap each condition in ().
  • sort_values sorts rows.
  • head/tail preview quickly.
๐Ÿ’ก Note: Forgetting parentheses around each condition is one of the most common pandas errors.

๐Ÿ“ Quick Quiz

1. AND in a pandas mask is:

2. Sort a DataFrame by column x with:

3. Each condition in a combined mask should be: