Section 3 · Lesson 2

Selecting, filtering and sorting

Pick columns, keep the rows that match a condition with boolean masks and .loc, and sort the result.

35 min 3 practice tasks
Python Pandas Tutorial (Part 4): Filtering - Using Conditionals to Filter Rows and Columns by Corey Schafer on YouTube

Most questions start with “show me only…”: only active campaigns, only completed orders, only these three columns. In pandas, that means selecting columns and filtering rows.

Selecting columns

import pandas as pd

campaigns = pd.read_csv("campaigns.csv")
orders = pd.read_csv("orders.csv")

campaigns["name"]                         # one column → a Series
campaigns[["name", "channel"]]            # a list of columns → a DataFrame

The double brackets aren’t special syntax: the outer brackets select, and the inner ones are an ordinary Python list of column names.

Filtering rows with a boolean mask

Compare a column to a value and pandas checks every row, giving you a Series of True/False values called a mask:

is_search = campaigns["channel"] == "search"
is_search.head(3)
# 0    False
# 1     True
# 2     True

Put the mask inside square brackets to keep only the rows where it’s True:

search = campaigns[is_search]
# or in one step:
search = campaigns[campaigns["channel"] == "search"]

Combining conditions

Inside pandas you can’t use Python’s and/or/not. Use these operators instead, and wrap each condition in parentheses:

Operator Meaning Example
& and (df["status"] == "active") & (df["channel"] == "search")
| or (df["channel"] == "search") | (df["channel"] == "social")
~ not ~(df["status"] == "ended")

The parentheses matter: & is evaluated before ==, so without them Python tries to compute "active" & df["channel"] and fails with a confusing error.

Two shortcuts save typing:

campaigns[campaigns["channel"].isin(["search", "social"])]          # one of several values
campaigns[campaigns["daily_budget"].between(500, 1000)]             # inclusive range

.loc: rows and columns together

.loc[rows, columns] selects by label. The rows part can be a mask, and the columns part a list of names, so you can filter and trim in one step:

campaigns.loc[campaigns["daily_budget"] >= 1000, ["name", "channel", "daily_budget"]]
campaigns.loc[:, ["name", "status"]]      # ":" means all rows

.loc is also the safe way to change values for some rows:

campaigns.loc[campaigns["status"] == "paused", "daily_budget"] = 0

Tip: Avoid “chained” assignment like campaigns[mask]["daily_budget"] = 0. The first brackets create a new DataFrame, so the change never reaches campaigns. Current pandas (with copy-on-write) leaves campaigns unchanged and prints a ChainedAssignmentError warning. Do it in one step with .loc.

Sorting

orders.sort_values("amount")                                   # smallest first
orders.sort_values("amount", ascending=False).head(10)         # top 10 by amount
campaigns.sort_values(["channel", "daily_budget"], ascending=[True, False])

Sorting by several columns works like sorting a spreadsheet: first by channel A→Z, then within each channel by budget, high to low.

Sorting keeps each row’s original index label, so the index on the left will look shuffled. Add .reset_index(drop=True) if you want it renumbered 0, 1, 2…

Putting it together

A typical question: Which five completed orders were largest?

completed = orders[orders["status"] == "completed"]
top5 = completed.sort_values("amount", ascending=False).head(5)
top5[["id", "customer_id", "amount"]]

Filter, sort, pick columns: you’ll chain these three moves in nearly every analysis.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

2

Big budgets with .loc

Load campaigns.csv into campaigns. Using .loc, create big_budgets: the campaigns with a daily_budget of 1000 or more, showing only the columns name, channel and daily_budget, in that order.

Need a hint?
  1. .loc[rows, columns]: rows can be a boolean mask, columns a list of names.
  2. campaigns.loc[campaigns["daily_budget"] >= 1000, ["name", "channel", "daily_budget"]]
Python 3
import pandas as pd

campaigns = pd.read_csv("campaigns.csv")

big_budgets = campaigns.loc[:, ["name"]]
print(big_budgets)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Top 10 completed orders

Load orders.csv into orders. Create top_orders: the 10 largest completed orders (status "completed"), sorted by amount from largest to smallest, with all columns.

Need a hint?
  1. Filter first: orders[orders["status"] == "completed"].
  2. .sort_values("amount", ascending=False) puts the largest first.
  3. .head(10) keeps the first ten rows of the sorted result.
Python 3
import pandas as pd

orders = pd.read_csv("orders.csv")

top_orders = orders.head()
print(top_orders)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country