…
…
Statistics and Data Analysis Fundamentals · Lesson 15 / 44 · Spread, shape, and charts
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Customer service wants to put a promise on the Bazaar site: "Your order arrives within … days." The mean delivery time (2.98 days) cannot go into this sentence, because about one order in three arrives later than 3 days. In this lesson you will find the number for the promise, and you will use a boxplot to see which carrier breaks it.
At the end of the lesson you will be able to give customer service a note like this:
Output90% of orders are delivered within 4 days.
With Arrow Express, 90% arrive within 3 days; with Gull Post, 4; with Caravan Freight, 5.Next to the note, you will have a boxplot that shows the delivery times of the three carriers side by side.
In this lesson you will:
quantile, and read them from a cumulative percent table.In lesson 14 you measured spread with the standard deviation, and you ended the lesson with a question: a customer does not ask "how many days does it take on average?" The customer asks "what is the latest it can arrive?" The mean is 2.98 days. If you write this number as a promise, you break it for a large share of the orders. You could also say "every order arrives within 7 days" (the slowest delivery took 7 days), but that promise tells nobody anything. One slow package would force you to give every customer a poor promise. The number you need is between the two: a limit that covers most of the orders but does not depend on one extreme value. This limit is called a percentile.
Imagine that you sort all the values of a variable from smallest to largest. The p-th percentile is the value that p% of the data is at or below. The 90th percentile is the value at nine tenths of the line. Only the last tenth is larger than it. The median from lesson 12 is also a percentile: the 50th percentile.
There is a common confusion here: the 90th percentile is a value, not a percent, and its unit is the unit of the data. The 90th percentile of delivery time is not "90%". It is "4 days". "90th" is only the name of the place in the line.
The most natural way to find a percentile is to add a column to the frequency table from lesson 11: the cumulative percent up to each delivery day. cumsum() gives the running total of a column up to each row (1 day, 1 + 2 days, 1 + 2 + 3 days, and so on). When you divide it by the total number of orders, you get "the percent of orders that arrive within this many days". Delivery time is empty for canceled orders (34 orders), so we first take the 851 filled values with dropna():
import pandas as pd s = pd.read_csv("orders.csv") t = s["delivery_days"].dropna() f = t.value_counts().sort_index() table = pd.DataFrame({"count": f, "cumulative_pct": (f.cumsum() / f.sum() * 100).round(1)}) print(table)
Output count cumulative_pct
delivery_days
1.0 87 10.2
2.0 212 35.1
3.0 275 67.5
4.0 196 90.5
5.0 70 98.7
6.0 10 99.9
7.0 1 100.0Read the table row by row: 10.2% of the orders arrive in 1 day, 35.1% within 2 days, and 67.5% within 3 days. The cumulative percent table is the percentile in table form.
Customer service wants to write "90% of orders are delivered within … days." According to the table, how many days go in the blank?
In pandas, the method that gives a percentile without building a table is quantile. You write the percent as a fraction between 0 and 1: 0.9 for the 90th percentile. s["delivery_days"].quantile(0.9) gives 4.0 days. quantile skips empty values by itself. Check it in the cell below, then try other percentiles:
Try it now· not graded; doesn't affect progress
Three percentiles are used so often that they have special names: the 25th percentile is the first quartile (Q1), the 50th is the median, and the 75th is the third quartile (Q3). These three values split the data into four parts, and each part holds a quarter of the observations. For the Bazaar order amounts:
import pandas as pd s = pd.read_csv("orders.csv") print(s["amount"].quantile([0.25, 0.5, 0.75]))
Output0.25 22.35
0.50 44.95
0.75 83.95
Name: amount, dtype: float64A quarter of the orders are below $22.35, half are below $44.95, and three quarters are below $83.95. The smallest order is $5.81 and the largest is $899.90. Now look at the widths of the four parts: from the smallest to Q1 it is $16.54, from Q1 to the median $22.60, from the median to Q3 $39.00, and from Q3 to the largest $815.95. The parts hold equal crowds (about 221 orders each), but they are far from equal in width. This corrects the most common mistake about quartiles: the four parts do not have the same width. What is equal is the number of observations. The widths also grow toward the right, and that is the trace in the numbers of the long right tail you saw in the histogram in lesson 11.
degistir blocks cannot read files, so below we use a 60-order sample of Bazaar amounts (the sample from lesson 11, in the same dollar scale). Change the percent and watch how the sentence changes each time:
Change p: in the 60-order sample, what is the amount at the p-th percentile, and what does the sentence say?
Pick a value; predict the output first, then look.
1import pandas as pd2p = 0.253amount = pd.Series([44.95, 71.95, 22.45, 449.95, 27.9, 164.95, 164.95, 49.45, 58.45, 15.95,4 40.45, 359.95, 64.95, 21.45, 44.95, 26.9, 54.9, 44.95, 191.9, 29.95,5 27.45, 229.9, 124.95, 31.9, 13.95, 64.95, 89.9, 449.95, 59.95, 124.95,6 329.9, 59.95, 114.95, 47.95, 44.95, 259.8, 50.35, 40.45, 44.95, 58.45,7 27.45, 13.45, 129.9, 9.95, 12.45, 359.95, 34.95, 14.95, 18.9, 27.9,8 114.95, 14.95, 215.8, 7.95, 54.95, 114.95, 94.95, 899.9, 114.95, 53.95])9value = round(amount.quantile(p), 1)10print("Percentile:", round(p * 100))11print(f"{round(p * 100)}% of the orders are at most ${value}")
Percentile: 25 25% of the orders are at most $27.9
Faded lines didn't run with this value. As p grows, the value grows, but not in equal steps: from 25 to 50 it grows by $26.50, and from 90 to 99 by more than $360. The 99th percentile, $634.4, is an amount that does not appear in the sample: quantile fills in the space between two neighboring values.
The $634.4 on the last line is not an amount that appears in the sample. When a percentile falls between two values, quantile calculates the point in between. Different programs can find this in-between point with slightly different methods, so in a small dataset the results can differ by a few units. In this lesson we use the pandas default.
The quartiles give a measure of spread: the interquartile range, or IQR for short. IQR = Q3 − Q1. It tells you how wide a range the middle half of the data covers. For the amount, 83.95 − 22.35 = $61.60: the middle half of the typical orders sits in a band that is $61.60 wide.
The difference between the IQR and the standard deviation is exactly in this comparison. In lesson 14 you saw that the standard deviation is sensitive to extreme values: each value enters the calculation with the square of its distance from the mean, so one giant order makes the standard deviation larger. The IQR looks only at Q1 and Q3. It does not care what happens in the outer quarters.
import pandas as pd s = pd.read_csv("orders.csv") x = s["amount"] q1 = x.quantile(0.25) q3 = x.quantile(0.75) print(round(q3 - q1, 1), round(x.std(), 1))
Output61.6 101.2The standard deviation of the amount is $101.2, which is even higher than the mean ($75.5). A few big orders inflate it. The IQR is $61.6. Now run an experiment: multiply the largest order by ten and calculate both again. We work on a copy (copy(), lesson 9), so the original table does not change:
Try it now· not graded; doesn't affect progress
The standard deviation jumps from $101.2 to $315.4, and the IQR stays at $61.6. This is why, for skewed data, the median is reported for the center and the IQR for the spread: "The typical order is $44.95; the middle half of the orders are between $22.35 and $83.95." For symmetric data without extreme values, the mean and standard deviation also work well. You will settle which one to choose, and when, in lesson 16 by looking at the shape of the distribution.
The IQR is also used to compare groups. Let's look at the delivery times of the carriers:
import pandas as pd s = pd.read_csv("orders.csv") g = s.groupby("carrier")["delivery_days"] print(pd.DataFrame({"Q1": g.quantile(0.25), "median": g.median(), "Q3": g.quantile(0.75)}))
Output Q1 median Q3
carrier
Arrow Express 2.0 2.0 3.0
Caravan Freight 3.0 4.0 5.0
Gull Post 2.0 3.0 4.0With Arrow Express, the middle half of the orders is between 2 and 3 days (IQR 1 day). With Gull Post it is between 2 and 4 days, and with Caravan Freight between 3 and 5 days (IQR 2 days each). Arrow Express is both faster and in a narrower band.
You can summarize a variable with five numbers: the smallest value, Q1, the median, Q3, and the largest value. The boxplot is the picture of this summary. The statistician John Tukey made this chart popular in the 1970s, and it works like a bird's-eye summary of a histogram. Here is how to read its parts:
Be careful: the whiskers do not always reach the smallest and largest values. They do if there are no far observations. If there are, the whisker stays short and the far observations become dots. Whether those dots are mistakes or real but unusual observations is a separate decision, which you will make in lesson 21. Here we only read what the chart shows.
In matplotlib, a boxplot is drawn with ax.boxplot(...). The line that draws the chart also returns a dictionary with the information about the whiskers and the dots. Below we save it as b and print where the whiskers end and how many dots there are:
import pandas as pd import matplotlib.pyplot as plt s = pd.read_csv("orders.csv") fig, ax = plt.subplots() b = ax.boxplot(s["amount"]) ax.set_ylabel("Amount ($)") print([float(w.get_ydata()[1]) for w in b["whiskers"]]) print(len(b["fliers"][0].get_ydata()))
Output[5.81, 170.91]
73The box is between $22.35 and $83.95, and the line inside it is at $44.95. The lower whisker goes down to the smallest order ($5.81); there are no far observations below. The limit that the upper whisker can reach is Q3 + 1.5 × IQR = 83.95 + 92.40 = $176.35. The largest order under this limit is $170.91, so the whisker ends there. The 73 orders above it are drawn one by one as dots, and they form a column of dots in the upper part of the chart that reaches up to $900. Delivery time looks different: the box is between 2 and 4 days, the IQR is 2 days, and the whiskers can reach at most 3 days from the box. The 1-day and 7-day deliveries are inside this limit, so the whiskers go all the way to the smallest and largest values, and there are no dots.
Match each part of the boxplot with its meaning.
For each row, pick its match from the list, then check.
A single boxplot says less than a histogram. The real strength of the boxplot is comparison: you put several groups on the same axis and read their medians and box heights at a glance. You give ax.boxplot a list with the values of each group, and you name the boxes with tick_labels:
import pandas as pd import matplotlib.pyplot as plt s = pd.read_csv("orders.csv") carriers = sorted(s["carrier"].unique()) groups = [s.loc[s["carrier"] == c, "delivery_days"].dropna() for c in carriers] fig, ax = plt.subplots() b = ax.boxplot(groups, tick_labels=carriers) ax.set_ylabel("Delivery time (days)") print([float(m.get_ydata()[0]) for m in b["medians"]]) print(s.groupby("carrier")["delivery_days"].quantile(0.9))
Output[2.0, 4.0, 3.0]
carrier
Arrow Express 3.0
Caravan Freight 5.0
Gull Post 4.0
Name: delivery_days, dtype: float64The groups list holds the delivery times of each carrier (with dropna(); you will see why below). In the chart, the Arrow Express box is the lowest and the shortest, and the Caravan Freight box is the highest. The medians are 2, 4, and 3 days, and the 90th percentiles are 3, 5, and 4 days. Now the promise for customer service is clear: "With Arrow Express, 90% of orders are delivered within 3 days; with Caravan Freight, within 5 days." The carrier that breaks the general promise of the site (4 days) is Caravan Freight.
In two boxplots side by side, the box of group A is twice as tall as the box of group B. Is the statement "Group A has more orders" correct?
In the cell below, draw the carrier chart, then try other groups and other variables:
Try it now· not graded; doesn't affect progress
In the device comparison, the two medians are almost the same ($44.95 and $44.90), but the desktop box reaches higher. The right reading: the typical order is the same size on both devices, and expensive orders are more common on desktop. The conclusion "desktop users are richer" does not come from the chart: the chart shows order amounts, not people's income.
A boxplot does not belong only to shopping. Let's look at the scores of two classes on the same exam (20 students each, with the scores typed by hand in lists):
import pandas as pd import matplotlib.pyplot as plt class_a = [72, 65, 80, 67, 77, 55, 73, 70, 88, 72, 63, 77, 68, 84, 60, 74, 67, 79, 71, 75] class_b = [91, 48, 72, 61, 100, 66, 83, 15, 94, 58, 72, 87, 52, 98, 64, 91, 69, 78, 61, 96] for name, scores in [("A", class_a), ("B", class_b)]: n = pd.Series(scores) print(name, n.median(), n.quantile(0.75) - n.quantile(0.25)) fig, ax = plt.subplots() b = ax.boxplot([class_a, class_b], tick_labels=["Class A", "Class B"]) ax.set_ylabel("Exam score") print(b["fliers"][1].get_ydata())
OutputA 72.0 10.0
B 72.0 30.0
[15]The medians of the two classes are the same: 72. The "typical student" got the same score in both classes. But in class A the middle half is in a band of 10 points (67 to 77), and in class B in a band of 30 points (61 to 91). In class B, the differences between students are much larger. One student got 15, and that student appears in the chart as a single dot far from the box. For the teacher, the two classes are not the same: in A everyone is in the same place, and in B there are both very strong students and students who need support.
Put the lines that draw the boxplot of delivery time by carrier in the correct order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
When we built the groups list, we used dropna() in every group. Why? pandas methods such as quantile and median skip empty values by themselves, but matplotlib's boxplot does not.
You wrote ax.boxplot(s["delivery_days"]); the column has 34 empty (NaN) values from canceled orders. What happens?
This trap is sneaky because no error message appears: the code runs, and the chart is just empty. When a boxplot comes out empty, the first place to look is whether the data contains empty values.
Now you can describe the center and the spread of a distribution in two different languages: the mean with the standard deviation, or the median with the IQR. The first pair uses all the values and is sensitive to extreme values. The second pair is based on order and is not affected by extreme values. For a balanced variable such as delivery time, the two languages tell a similar story. For a right-skewed variable such as order amount, the median with the IQR is more honest. When you promise a customer or a manager "at the latest" or "most of the time," you use a percentile directly: "90% of orders are delivered within 4 days." This sentence says nothing about the remaining 10%. If you wonder how late those orders are, you look at the 99th percentile or the largest value.
In lesson 4, we left the 25%, 50%, and 75% rows of the describe() output for later. Now you can read them.
import pandas as pd s = pd.read_csv("orders.csv") print(s["delivery_days"].describe().round(2))
Outputcount 851.00
mean 2.98
std 1.16
min 1.00
25% 2.00
50% 3.00
75% 4.00
max 7.00
Name: delivery_days, dtype: float64The 25%, 50%, and 75% rows are Q1, the median, and Q3. Together with min and max, you have the five numbers of the boxplot in one output: 1, 2, 3, 4, 7. The IQR is 4 − 2 = 2 days. count is 851 because describe() also skips empty values.
The Bazaar product team tracks the speed of the checkout page. For the 195 sessions that reached the checkout page, the file
Drawing a boxplot with a column that contains missing values. The code below raises no error but produces an empty axis, because delivery_days is empty for canceled orders:
Outputfig, ax = plt.subplots()
ax.boxplot(s["delivery_days"])The correct way is to drop the empty values first: ax.boxplot(s["delivery_days"].dropna()). Also note how many observations were dropped (here, 34 canceled orders). The second common mistake is to think that the line inside the box is the mean: that line is the median.
quantile(0.9), and it lets you write a promise such as "90% of orders are delivered within 4 days." The quartiles (Q1, median, Q3) split the data into four parts with equal crowds, but usually not equal widths.dropna() before you draw it.Next lesson: Mean and standard deviation, or median and IQR? The answer is in the shape of the distribution, and skewness and the z-score come next.
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.
sessions.csvimport pandas as pd o = pd.read_csv("sessions.csv") print(o["checkout_time_sec"].count()) print(o["checkout_time_sec"].quantile([0.25, 0.5, 0.75, 0.9]))
Output195
0.25 93.5
0.50 114.0
0.75 141.0
0.90 161.0
Name: checkout_time_sec, dtype: float64Half of the customers finish the payment in 114 seconds, and 90% in 161 seconds. If the team's goal is "90% of payments in under 2 minutes," the result is 41 seconds short of the goal. The IQR is 141 − 93.5 = 47.5 seconds: typical payment times are spread over a band of about 50 seconds.