…
…
Statistics and Data Analysis Fundamentals · Lesson 14 / 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.
In customer reviews, the most common complaint is delivery. The mean delivery times of Bazaar's three carriers are 2.25, 3.12, and 3.90 days, but customers care about more than the mean: they want to know when their package will arrive. In this lesson you will measure how widely the values are spread around the mean, and you will answer "which one is more predictable?" with a number.
By the end of this lesson you will produce the table below yourself and write the sentence under it:
Output mean std cv
carrier
Arrow Express 2.25 0.88 0.39
Caravan Freight 3.90 1.00 0.26
Gull Post 3.12 0.99 0.32"Arrow Express delivery times are typically 0.9 days away from the mean of 2.25 days. The spread of the three carriers is close to each other in days. Arrow Express's real advantage is speed."
In this lesson you will:
In lesson 12 you measured the center of a distribution: mean, median, mode. In the histograms of lesson 11 you saw one more thing: some distributions gather in a narrow band, and some spread over a wide area. The center alone does not tell you this difference. Imagine three small carriers. Each one carried five packages. Here are the delivery times in days:
import pandas as pd for days in [[3, 3, 3, 3, 3], [2, 3, 3, 3, 4], [1, 1, 3, 5, 5]]: x = pd.Series(days) print(x.mean(), x.max() - x.min())
Output3.0 0
3.0 2
3.0 4All three carriers have a mean of 3 days. With the first carrier, every package arrives in exactly 3 days. With the third, some packages arrive on the next day and some on the fifth day. If a customer asks the first carrier "when will my package arrive?", the answer is exact. If they ask the third, they hear "between 1 and 5 days". How far the values are from each other and from the center is called spread. When you describe a distribution, you give the center and the spread together. Each one alone tells only half of the story.
The three lists have the same mean (3 days): [3, 3, 3, 3, 3], [2, 3, 3, 3, 4], [1, 1, 3, 5, 5]. With which carrier does a customer get the most uncertain answer to "when will my package arrive?"
The simplest measure of spread is the range: the largest value minus the smallest value. In pandas you write x.max() - x.min(). In the three carriers above, the range is 0, 2, and 4 days. It is easy to calculate and easy to understand: "there are 4 days between the fastest package and the slowest package."
The range does not use all the data. It uses only the largest and the smallest value. Whatever the values in between are, the result does not change. For this reason, a single extreme value decides the range alone:
import pandas as pd a = pd.Series([2, 3, 3, 3, 4]) b = pd.Series([2, 3, 3, 3, 14]) print(a.max() - a.min(), b.max() - b.min()) print(a.median(), b.median())
Output2 12
3.0 3.0In the two lists, four of the five packages are the same. Only the last package arrived in 14 days instead of 4. The range jumped from 2 to 12: it became six times larger. But the experience of most packages did not change at all (the median is 3 in both lists). The range tells you "the distance between the worst case and the best case". It does not tell you the typical experience.
In Bazaar's order amounts, this effect is very large. The smallest order is $5.81 and the largest is $899.90, so the range is $894.09. Almost all of this number comes from a few expensive Electronics orders. Three orders are exactly $899.90: two robot vacuums at $449.95 each. Below, remove the few orders of $500 or more and see how much the range changes:
Try it now· not graded; doesn't affect progress
Removing only 6 of the 885 orders cuts the range from $894.1 to $494.0, nearly half. The "standard deviation" in the second line changed too, but by less (from 101.2 to 80.1). The standard deviation uses all the values. Now let's build it step by step.
To fix the weakness of the range, we need to look at how far each value is from the mean. Take the delivery times of the third carrier: [1, 1, 3, 5, 5], mean 3.
1. Deviations: Subtract the mean from each value: −2, −2, 0, 2, 2. A minus sign means "came before the mean", a plus sign means "came after".
2. You cannot average the deviations: Their sum is always 0. The pluses and minuses cancel each other. This follows from the definition of the mean (the mean is the point where the deviations balance).
3. Squares: Square each deviation: 4, 4, 0, 4, 4. Squaring removes the minus sign. It also gives more weight to distant values (a 2-day deviation counts as 4, a 4-day deviation counts as 16).
4. Variance: Divide the sum of the squares (16) by the number of observations minus one (5 − 1 = 4): 16 / 4 = 4. This number is called the variance. Why 4 and not 5? We also calculate the mean from the same data, so the deviations come out a little small. Dividing by one less corrects this. You will see the details in lesson 25.
5. Square root: The unit of the variance is "days²", and "square days" means nothing to anyone. With the square root, the unit is days again: √4 = 2. This number is the standard deviation.
Follow the code below line by line. See that the sum of the deviations really comes out 0, and how the squares and the variance form. Then change the list to [2, 3, 3, 3, 4] and trace it again.
Run the code line by line: see which line runs next, the variable boxes and the output.
days = [1, 1, 3, 5, 5] n = len(days) mean = sum(days) / n deviations = [d - mean for d in days] print("Deviations:", deviations) print("Sum of deviations:", sum(deviations)) squares = [d ** 2 for d in deviations] print("Squares:", squares) variance = sum(squares) / (n - 1) std = variance ** 0.5 print("Variance:", variance) print("Standard deviation:", std)
Now put the steps of the same calculation in order yourself:
Put the lines that calculate the standard deviation by hand 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
Be careful how you read the standard deviation. The sentence "the standard deviation is 2 days" does not mean "every package is exactly 2 days away from the mean". In the example above, one package did not deviate at all (3 days), and four deviated by 2 days. It does not mean "the mean error is 2 days" either. There is no error here. The values are simply different. The correct reading is: the values are typically 2 days away from the mean. Some are closer, some are farther. The standard deviation is a kind of "average distance" of them (because it is calculated with squares, it is not exactly the average distance, but a summary close to it).
The hand calculation was to understand the idea. With real data, pandas does it in one call: x.std() gives the standard deviation and x.var() gives the variance. Both divide by n − 1 by default, so they give the same result as the hand calculation above:
import pandas as pd days = pd.Series([1, 1, 3, 5, 5]) print(days.var(), days.std())
Output4.0 2.0Now try the lists of the three carriers one by one. The mean stays 3 days. What do the range and the standard deviation do?
Delivery times of three carriers. While the mean stays the same, how do the range and the standard deviation change?
Pick a value; predict the output first, then look.
1import pandas as pd2days = [3, 3, 3, 3, 3]3x = pd.Series(days)4print("Mean:", x.mean())5print("Range:", x.max() - x.min())6print("Standard deviation:", round(x.std(), 2))
Mean: 3.0 Range: 0 Standard deviation: 0.0
Faded lines didn't run with this value. The farther the values are from the mean, the bigger the standard deviation is. If all the values are the same, it is 0. The range of the last two lists is the same (4 days), but their standard deviations are different: in the list [1, 3, 3, 3, 5] only two ends are far, and in the list [1, 1, 3, 5, 5] four values are far. The range does not see this difference. The standard deviation does.
If the standard deviation is 0, all the values are the same. There is no spread at all. The standard deviation is never negative, because it comes from a sum of squares.
On the same data, pandas x.std() gives 1.159 and NumPy np.std(x) gives 1.1583. Why?
Now let's go back to the case. For each carrier, let's calculate the mean and the standard deviation of the delivery time with groupby (the agg list from lesson 7):
import pandas as pd orders = pd.read_csv("orders.csv") g = orders.groupby("carrier")["delivery_days"].agg(["mean", "std"]) g["cv"] = g["std"] / g["mean"] print(g.round(2))
Output mean std cv
carrier
Arrow Express 2.25 0.88 0.39
Caravan Freight 3.90 1.00 0.26
Gull Post 3.12 0.99 0.32Let's read the first two columns. Arrow Express delivery times are typically 0.88 days away from the mean of 2.25 days. For Gull Post it is 0.99, and for Caravan Freight it is 1.00 day. In days, the spread of the three carriers is very close: for all of them, the packages are typically about one day away from the mean. So on the question "how much can my package differ from the mean?", there is no big difference between the carriers. Arrow Express is a little narrower. Arrow Express's real advantage is not in its spread but in its speed (mean 2.25 days). This is also like the lesson of lesson 12: do not talk with a single number, talk with the center and the spread together.
The third column (cv) is new: the standard deviation divided by the mean. We will come to it in a moment. First, produce your own table and try it on another variable:
Try it now· not graded; doesn't affect progress
Looking at the order amount by category, the table is this:
import pandas as pd orders = pd.read_csv("orders.csv") g = orders.groupby("category")["amount"].agg(["mean", "std"]) g["cv"] = g["std"] / g["mean"] print(g.round(2))
Output mean std cv
category
Beauty 27.89 24.22 0.87
Books 21.80 15.56 0.71
Clothing 68.53 55.82 0.81
Electronics 146.48 179.90 1.23
Home & Living 93.10 87.72 0.94The standard deviation of Electronics is $179.90 and that of Books is $15.56: more than eleven times. Is it right to say "Electronics orders are eleven times more volatile"? No. In Electronics, the amounts themselves are big: the mean is $146.48. A change of $15 is big for a book order and small for a smartwatch order. A big standard deviation also does not mean bad or wrong data. In this category the prices cover a wide range, from a $19.95 tablet case to a $449.95 robot vacuum, and the standard deviation reflects this.
To measure relative spread, you use the coefficient of variation: the standard deviation divided by the mean. It has no unit (dollars divided by dollars), so it can compare groups with different scales. For Electronics it is 1.23 and for Books it is 0.71. Electronics is also more variable in relative terms, but the difference is not eleven times, it is about 1.7 times. The standard deviations were exaggerating the difference in scale.
Going back to the carrier table, you see something interesting: Arrow Express has the smallest standard deviation (0.88 days) but the biggest coefficient of variation (0.39). This is because its mean is also the smallest. A 0.9-day swing in a time of 2.25 days is relatively bigger than a 1-day swing in a time of 3.90 days. The group with the smaller standard deviation does not have to be less variable in relative terms. Which one will you use? If the customer asks "how many days can it differ?", the answer must be in days: the standard deviation. If you compare groups whose means are very different (Books and Electronics, grams and kilograms, a student's allowance and a company's revenue), use the coefficient of variation.
Here are the grades of Ada and Bora on five exams:
import pandas as pd ada = pd.Series([70, 72, 68, 71, 69]) bora = pd.Series([40, 100, 55, 95, 60]) print(ada.mean(), round(ada.std(), 2)) print(bora.mean(), round(bora.std(), 2))
Output70.0 1.58
70.0 26.22Both have a mean of 70. Ada's grades are typically 1.6 points away from 70. It makes sense to expect a grade around 70 on her next exam. Bora's grades are typically 26 points away. On the next exam he can get 40 or 100. Saying "both are students with a mean of 70" does not tell much to Bora's teacher or to Bora. Here the means of the two groups are the same and the unit is the same (points). Comparing the standard deviations directly is enough. You do not need the coefficient of variation.
Match each situation with the measure you would use.
For each row, pick its match from the list, then check.
The standard deviation uses all the values. This is better than the range. But because it is built on the mean, it carries the weakness of the mean too: it is sensitive to extreme values. Also, because of the squares, it gives extra weight to distant values. Look at Bazaar's amounts:
import pandas as pd orders = pd.read_csv("orders.csv") amount = orders["amount"] print(round(amount.mean(), 1), round(amount.std(), 1), amount.median())
Output75.5 101.2 44.95The standard deviation ($101.2) is even above the mean ($75.5). The sentence "orders are typically $101.2 away from the mean" is technically correct, but it sounds strange. Half of the orders are under $45, and nobody pays a negative amount like 75.5 − 101.2. A few big orders inflate this number. In section 2, when we removed 6 orders, it went down to $80.1. In a skewed distribution with a long right tail, like in lesson 11, the pair of mean and standard deviation does not describe the picture well.
The customer does not really ask "how far from the mean can it be?" either. They ask "what is the latest it can arrive?" The answer to this question, and a robust way to describe spread in skewed data, is quartiles and the interquartile range (IQR): the topic of the next lesson.
Let's put the range and the standard deviation side by side for the carriers.
import pandas as pd orders = pd.read_csv("orders.csv") t = orders.groupby("carrier")["delivery_days"].agg(["min", "max", "std"]) t["range"] = t["max"] - t["min"] print(t.round(2))
Output min max std range
carrier
Arrow Express 1.0 4.0 0.88 3.0
Caravan Freight 1.0 7.0 1.00 6.0
Gull Post 1.0 6.0 0.99 5.0Someone who looks at the range says "Caravan Freight is twice as scattered as Arrow Express." But Caravan Freight has only one delivery of 1 day and one of 7 days (out of 226 packages). Most of the packages take between 3 and 5 days. The standard deviations (0.88 and 1.00) show that the difference is much smaller. The range looks at two packages. The standard deviation looks at all the packages.
Let's calculate the standard deviation of delivery time with the two libraries. In canceled orders the delivery time is empty, so first we drop the empty values with dropna() (NumPy gives no result when it sees an empty value).
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") x = orders[].dropna() ((x.std(), 4), (np.std(x.to_numpy()), 4), (np.std(x.to_numpy(), ddof=1), 4))
Comparing the variability of groups with very different means by their standard deviation. The following sentence is wrong:
OutputThe standard deviation of Electronics is $179.90 and that of Books is $15.56;
Electronics customers are eleven times more inconsistent.A big standard deviation first shows that the amounts are big. The corrected sentence: "The coefficient of variation is 1.23 for Electronics and 0.71 for Books. Electronics order amounts are also more variable relative to their mean, but the difference is about 1.7 times." Also note: the data does not say the customers are "inconsistent". It says the amounts of the orders change. In Electronics, the price range is wide.
std() divides by n − 1 and np.std() divides by n (they become equal with ddof=1).Next lesson: The customer asks "what is the latest it can arrive?" With quartiles, the IQR, and the box plot, you will describe spread in skewed data in a robust way.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output1.159 1.1583 1.159With 851 observations, the difference is in the fourth decimal place. The difference between n − 1 and n becomes unimportant in large data. In a list of five observations, however, the difference is big (you will see it in the exercises).