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.
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 reachescampaigns. Current pandas (with copy-on-write) leavescampaignsunchanged and prints aChainedAssignmentErrorwarning. 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.
Active search campaigns
DoneLoad campaigns.csv into campaigns. Create a DataFrame active_search containing only the campaigns whose status is "active" and whose channel is "search". Keep all the columns.
Need a hint?
- Build one mask per condition:
campaigns["status"] == "active". - Combine masks with
&and wrap each condition in parentheses. - Put the combined mask inside
campaigns[...]to keep matching rows.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
campaigns = pd.read_csv("campaigns.csv")
active_search = campaigns # filter me
print(active_search)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)Big budgets with .loc
DoneLoad 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?
.loc[rows, columns]: rows can be a boolean mask, columns a list of names.campaigns.loc[campaigns["daily_budget"] >= 1000, ["name", "channel", "daily_budget"]]
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
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)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)Top 10 completed orders
DoneLoad 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?
- Filter first:
orders[orders["status"] == "completed"]. .sort_values("amount", ascending=False)puts the largest first..head(10)keeps the first ten rows of the sorted result.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
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)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)