…
…
Statistics and Data Analysis Fundamentals · Lesson 5 / 44 · DataFrames and selecting
PreviewIn this lesson you will
&, |, ~, isin, and between, pick the columns you want with loc, and order the result with sort_valuesYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In the previous lesson you opened Bazaar's 885 orders with a single line and got to know the table. The manager's question is about specific parts of the table: before and after May, on mobile and on desktop, by carrier. In this lesson you will learn to select exactly the rows and columns you want from a table, combine conditions, and sort the result.
By the end of this lesson you will have produced these two lines with your own code:
OutputMobile share (%): Jan–Apr 60.8 · May–Jun 50.5
5+ days delivery: 81 orders; Caravan Freight 59, Gull Post 22The first line answers the "period" and "breakdown" parts of the question you built in lesson 1: before the drop, what percent of orders came from mobile, and after it? The second line is a new clue: which carriers handled the orders that took 5 days or more to arrive? These two answers have one thing in common. Both look at a specific part of the table, not the whole table.
Most of data analysis is choosing the right part. In pandas, every selection answers three questions: which rows (only orders after May? only mobile?), which columns (all 13 columns, or only order_id and amount?), and in which order (the most expensive order first?). In this lesson you will learn the tools for these three questions, one by one.
In this lesson you will:
loc.When the manager asks, "How are the book orders doing?", you do not want to look at all 885 rows. You only need the rows whose category is Books. Think of it as two steps. First you ask every row a question: "Is the category of this row Books?" The expression df["category"] == "Books" does exactly this. It returns a Series of 885 elements, with True
Three orders have the same amount. To make the order of ties clear, the second key is order_id.
import pandas as pd df = pd.read_csv("orders.csv") top = df.sort_values(["amount", "order_id"], ascending=[False, True]) print(top[["order_id", "category", "amount"]].head(3))
Output order_id category amount
199 S00200 Electronics 899.9
434 S00435 Electronics 899.9
457 S00458 Electronics 899.9The three most expensive orders are all Electronics and have the same amount. ascending=[False, True] sorts the amount from large to small and, in a tie, sorts order_id from small to large.
A running club has 8 members. The members who run the 10K and finish in under 50 minutes, sorted by time:
import pandas as pd t = pd.DataFrame({ "name": ["Hana", "Marco", "Zara", "Alex", "Leo", "Lena", , ], : [24, 31, 19, 45, 28, 36, 22, 40], : [27.5, 48.2, 55.0, 44.9, 31.2, 49.5, 52.3, 26.8], : [, , , , , , , ], }) fast_10k = t.loc[(t[] == ) & (t[] < 50), [, ]] (fast_10k.sort_values())
Combining conditions without parentheses: df[df["device"] == "mobile" & df["category"] == "Clothing"]. Python runs & before == and raises a TypeError. Writing and also raises an error with a Series. The correct way is to put each condition in its own parentheses and use &, |, and ~: df[(df["device"] == "mobile") & (df["category"] == "Clothing")].
df[condition] selects the rows that meet the condition. The sum() of the condition Series gives the count, and the mean() gives the share. Periods of different length are compared with shares, not counts.& (and: narrows), | (or: widens), and ~ (not). isin selects one of several values, and between selects a range with both ends included. df.loc[condition, columns] selects rows and columns together.sort_values (with several columns and ascending=False) and nlargest sort. Filtering and sorting return a new table. When you write a share, write its denominator too.Next lesson: We can select now, but the table has no "month" column or "discounted?" column. We will learn to create new columns from the existing ones.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Falsedf[b]TrueLet's see how the sieve works on a small table:
| Row | Category | category == "Books" | Passed the sieve? |
|---|---|---|---|
| 0 | Home & Living | False | No |
| 3 | Books | True | Yes |
| 4 | Clothing | False | No |
A condition Series has a nice side product. In lesson 2 you saw that the mean of a 0/1 column gives a share. Python counts True as 1 and False as 0, so the sum() of a condition Series gives the number of rows that meet the condition, and the mean() gives their share. You can answer "how many?" and "what percent?" without filtering the table at all.
import pandas as pd df = pd.read_csv("orders.csv") b = df["category"] == "Books" print(b.head(3).tolist(), b.sum(), round(b.mean(), 3)) print(len(df[b]))
Output[False, False, False] 117 0.132
117The first three orders are not Books. In the whole table there are 117 Books orders, which is 13.2 percent of the orders. The filtered table also has 117 rows: b.sum() and len(df[b]) answer the same question in two ways.
What does (df["status"] == "returned").mean() give?
(df["status"] == "returned").mean()
Now it is your turn. In the cell below, change the condition and watch how the count and the share change.
Try it now· not graded; doesn't affect progress
At the heart of the manager's question is a period comparison: before May and after May. Bazaar's date column is still stored as a string. We will convert it to a real date type in lesson 6. We can already filter today, because the dates are written as YYYY-MM-DD. You remember from the Python course that strings are compared in dictionary order, character by character from left to right. The year comes first, the month is in the middle, the day is last, and all of them have the same length, so "2026-04-30" < "2026-05-01" gives the right result. The same trick does not work for dates with the day first, such as 30.04.2026, or with the month first, such as 04/30/2026.
Putting the two parts of the comparison into separate variables makes the code easier to read: before and after. Then you do the same calculation on each part.
import pandas as pd df = pd.read_csv("orders.csv") before = df[df["date"] < "2026-05-01"] after = df[df["date"] >= "2026-05-01"] print(len(before), len(after)) share_before = (before["device"] == "mobile").mean() * 100 share_after = (after["device"] == "mobile").mean() * 100 print(round(share_before, 1), round(share_after, 1))
Output669 216
60.8 50.5There are 669 orders in January–April and 216 in May–June. The mobile share went from 60.8 percent down to 50.5 percent. There is a trap here: it is tempting to look at the counts of mobile orders and say "it dropped from 407 to 109." But the first period is four months and the second is two months, so the counts already come from periods of different length. As you saw in lesson 1, periods of different length are compared either with a monthly average or with a share. A share answers "out of every 100 orders, how many come from mobile?" on the same scale for both periods.
Below you can see how fewer rows pass through the sieve as the threshold changes. The code uses 10 order amounts picked from Bazaar.
Change the threshold: how many orders pass the sieve, and what percent?
Pick a value; predict the output first, then look.
1import pandas as pd23threshold = 504amount = pd.Series([5.80, 15.95, 22.35, 44.95, 59.95, 74.95, 124.95, 199.95, 449.95, 899.90])5condition = amount >= threshold6print(condition.sum(), round(condition.mean() * 100, 1))
6 60.0
Faded lines didn't run with this value. As the threshold goes up, fewer orders pass the sieve: 6, 4, 2, 1. The count and the share come from the same condition Series: sum() gives how many are True, and mean() gives the share of Trues (each order is 10 percent of 10 orders).
Real questions often contain more than one condition: "Clothing orders that came from mobile," "orders shipped with Arrow Express or Gull Post," "orders that were not completed." In pandas, conditions are combined with three operators: & (and: both conditions are true), | (or: at least one is true), and ~ (not: reverses the condition). Each condition is written inside its own parentheses: (df["device"] == "mobile") & (df["category"] == "Clothing").
Why are the parentheses required? Python runs & before the == comparison. If you write it without parentheses, Python first tries a meaningless operation like "mobile" & df["category"] and raises an error. The and and or you learned in the Python course do not work here either. They need a single True/False, and the "single truth value" of a Series with 885 values is ambiguous, so pandas raises an error.
What happens when this line runs?
df[df["device"] == "mobile" & df["category"] == "Clothing"]
There are two short ways to write long chains of conditions. If you want a column to be one of several values, use isin instead of chaining with |: df["carrier"].isin(["Arrow Express", "Gull Post"]). For a range there is between: df["amount"].between(50, 100) includes both ends, so orders of exactly $50 and exactly $100 are selected too. Both methods return a boolean Series. You can use them inside square brackets or together with &.
import pandas as pd df = pd.read_csv("orders.csv") fast = df["carrier"].isin(["Arrow Express", "Gull Post"]) middle = df["amount"].between(50, 100) print(fast.sum(), middle.sum(), (fast & middle).sum()) print((~(df["status"] == "completed")).sum())
Output647 203 147
98647 orders went with Arrow Express or Gull Post, 203 orders have an amount between $50 and $100, and 147 orders meet both conditions. When you count the orders that are "not completed" with ~, you get 98: 64 returned and 34 canceled.
In everyday language, "and" sounds like adding something: when someone says "get the mobile and Clothing orders," some people think of the mobile orders plus the Clothing orders. In logic, it is the other way around: "and" narrows, "or" widens. & asks for rows that meet both conditions, so it returns fewer rows than either single condition. | asks for rows that meet any of the conditions, so it returns more rows than either one.
Bazaar has 516 mobile orders and 266 Clothing orders. "Mobile and Clothing" is the intersection of the two, 214 orders. "Mobile or Clothing" is the union of the two, 568 orders. Try the same idea yourself on a small table with six rows.
Change the operator: does "and" or "or" return more rows?
Pick a value; predict the output first, then look.
1import pandas as pd23operator = "and"4t = pd.DataFrame({5 "device": ["mobile", "mobile", "desktop", "mobile", "desktop", "desktop"],6 "category": ["Clothing", "Books", "Clothing", "Clothing", "Books", "Home & Living"],7})8a = t["device"] == "mobile"9b = t["category"] == "Clothing"10condition = (a & b) if operator == "and" else (a | b)11print(condition.sum(), t[condition].index.tolist())
2 [0, 3]
Faded lines didn't run with this value. "And" (&) keeps the 2 rows that meet both conditions (0 and 3). "Or" (|) returns the 4 rows that meet at least one. In Bazaar it is the same: mobile and Clothing is 214 orders, mobile or Clothing is 568 orders.
loc: selecting rows and columns togetherSo far, filtering has returned all the columns. Most of the time you do not need all 13 columns. order_id and amount are enough. loc selects rows and columns in one step: df.loc[rows, columns]. To the left of the comma you write a condition for the rows (or : for all of them). To the right you write a single column name or a list of column names.
import pandas as pd df = pd.read_csv("orders.csv") mobile_clothing = (df["device"] == "mobile") & (df["category"] == "Clothing") selection = df.loc[mobile_clothing, ["order_id", "amount"]] print(len(selection)) print(selection.head(3))
Output214
order_id amount
7 S00008 29.95
12 S00013 59.95
14 S00015 59.95The numbers 7, 12, and 14 on the far left are the index of the rows, which means their place in the original table. Filtering does not renumber the index. Every row keeps its number from the original table. This makes it easy to trace where a row came from.
Splitting an analysis into small steps reduces mistakes. The lines below do the job "count the deliveries of 5 days or more by carrier." Put them in the right order.
Put the lines of the code "count the deliveries of 5 days or more by carrier" in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Questions like "Which are the most expensive orders?" or "Which carrier has the longest deliveries?" need sorting. df.sort_values("amount") orders the table by amount from small to large, and ascending=False reverses it to large to small. If you pass a list, pandas looks at the first column first, and at the second column when there is a tie. Think of an exam results list: it is sorted by score first, and people with the same score are ordered by name. In Bazaar, three orders have exactly the same amount, $899.90. Without a second key, the order of these three stays undefined. So that the report looks the same every time it runs, order_id becomes the second key. You will see this example below, in Example 5. If you only need the few biggest rows, the short way is nlargest(3, "amount").
Filtering and sorting do not change the original table. They return a new table. If you write df.sort_values("amount") and do not assign the result to a variable, the sorted table is lost and df stays as it was. In the same way, after you write may = df[df["date"] >= "2026-05-01"], df still has 885 rows, and may is a separate new table with 216 rows. This is a good thing: you can cut as many parts as you want without damaging the original data.
Split a complex question into steps: first filter, then count, then sort. Let's solve the late delivery question this way.
import pandas as pd df = pd.read_csv("orders.csv") late = df["delivery_days"] >= 5 print(late.sum()) print(df.loc[late, "carrier"].value_counts())
Output81
carrier
Caravan Freight 59
Gull Post 22
Name: count, dtype: int6481 orders took 5 days or more to arrive. Of these, 59 went with Caravan Freight and 22 with Gull Post. Arrow Express is not in the list, because none of its orders passed this threshold. Extending the same question is up to you.
Try it now· not graded; doesn't affect progress
Your work is not finished when you find a number. You need to put it into a sentence. "81 late deliveries" alone does not tell you whether that is few or many. When you turn it into a share, the denominator starts to matter. late.mean() divides by all 885 orders. But 34 orders have an empty delivery_days value (the canceled ones). An empty value counts as False in a >= 5 comparison, so these orders enter the denominator as "not late." If you look among the 851 orders with a known delivery day, the share changes a little.
import pandas as pd df = pd.read_csv("orders.csv") late = df["delivery_days"] >= 5 print(round(late.mean() * 100, 1)) known = df.loc[df["delivery_days"].notna(), "delivery_days"] print(round((known >= 5).mean() * 100, 1))
Output9.2
9.5Both numbers are correct, but they answer different questions: "9.2 percent of all orders" and "9.5 percent of delivered orders." Always write the denominator in a report. notna() is a condition that gives True for rows that are not empty. We will work with empty values in detail in lesson 19.
The denominator question matters even more when you make a decision. Choose what you would do in the case below.
Customer support says, "Caravan Freight is very late." You have the late delivery counts: 59 of the 81 late deliveries are from Caravan Freight. What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
Selecting, filtering, and sorting are not specific to store data. In the member list of a running club, the question "members who run the 10K and finish in under 50 minutes, sorted by time" has the same three steps: combine two conditions with &, pick the name and time columns with loc, and sort with sort_values. You will see the code and its output in Example 7 below. With every new question, first turn the question into conditions. The code gets easier after that.
Match each question with the condition that answers it.
For each row, pick its match from the list, then check.
Output name time_min
3 Alex 44.9
1 Marco 48.2
5 Lena 49.5Three of the five 10K runners finished in under 50 minutes. Zara and Omar run the 10K, but their times are over 50. Hana and Maya are fast, but they run the 5K. "And" asks for both conditions.