…
…
Statistics and Data Analysis Fundamentals · Lesson 16 / 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.
At Bazaar, a $200 Electronics order and a $75 Books order came in; which one is more unusual in its own category? On the same day the marketing team reported an average daily ad spend of $157.11, but almost no day had spend close to that amount. In this lesson you will read the shape of a distribution, choose the summary that fits the shape, and say where an observation sits with a z-score.
By the end of this lesson you will be able to produce the table below and the two lines under it yourself:
OutputVariable Shape Summary to report
Order amount right-skewed, one peak median $44.95 and IQR $61.60
Delivery days nearly symmetric mean 2.98 days and std 1.16 days
Ad spend two peaks split the periods first
$200 Electronics order: z = 0.30 (ordinary in its category)
$75 Books order: z = 3.42 (very unusual in its category)In this lesson you will:
In lesson 11 you learned to describe a distribution with three questions: where is the center, how spread out is it, and what is its shape? In the next lessons you turned the first two questions into numbers: the center with the mean and the median (lesson 12), the spread with the standard deviation (lesson 14) and the quartiles (lesson 15). The third question is still answered in words: "the pile is on the left and there is a long tail to the right." In this lesson you will name the shape, see how the shape decides which summary numbers to use, and at the end you will say where an observation sits in its distribution with one number.
Why does shape matter? The mean and the standard deviation can be calculated for every distribution, but they do not say the same thing in every distribution. Look at three Bazaar variables: order amount, delivery days and recommend score. All three have a mean and a standard deviation, but their histograms look nothing alike. Choosing a summary without looking at the shape is like giving directions without looking at the map.
If a distribution is symmetric, the two sides of the central peak mirror each other: it stretches as far to the left as it does to the right. In a skewed distribution one side is much longer than the other, and that long, thin side is called the tail. The direction of the skew is the direction of the tail:
The most common mistake here is to name the direction by the pile. In the histogram of order amount, most bars gather on the left, so people tend to say "piled to the left, so left-skewed." But the name comes from the tail: the pile is on the left, the tail is on the right, and the distribution is right-skewed.
The sign you saw in lesson 12 helps here: the mean is pulled toward the tail, and the median stays in the middle of the sorted values. If the mean is clearly larger than the median, the tail is on the right; if it is clearly smaller, the tail is on the left; if the two are close, the distribution is nearly symmetric. In pandas, x.skew() gives the skewness coefficient: a positive sign means right-skewed, a negative sign means left-skewed, and a value near zero means nearly symmetric. You do not need to memorize thresholds for the size of the coefficient; look at the sign and read it together with the histogram.
Example 1 (case): the shape of three variables. Here are the mean, the median and the skewness of three Bazaar variables side by side:
import pandas as pd orders = pd.read_csv("orders.csv") survey = pd.read_csv("survey.csv") for name, x in [("amount", orders["amount"]), ("delivery", orders["delivery_days"]), ("recommend", survey["recommend_score"])]: print(name, round(x.mean(), 2), x.median(), round(x.skew(), 2))
Outputamount 75.53 44.95 4.18
delivery 2.98 3.0 0.19
recommend 7.51 8.0 -0.47In amount, the mean (75.53) is far above the median (44.95) and the skewness is 4.18: clearly right-skewed. In delivery days, the mean and the median are almost the same (2.98 and 3) and the skewness is 0.19: nearly symmetric. In the recommend score, the mean is a little below the median (7.51 and 8) and the skewness is −0.47: most customers give high scores, and a small number of low scores make a short tail on the left, so it is slightly left-skewed. The number and the sign tell the same story; reading them together reduces the chance of a mistake.
In a distribution, the mean is clearly larger than the median. What can you say?
A number summarizes the shape, but it is not enough on its own. Very different histograms can give the same skewness coefficient; in particular, the coefficient does not reveal a distribution with two peaks. So the rule is simple: histogram first, number second. Match the four descriptions below with the shape names:
Match each histogram description with the name of the shape.
For each row, pick its match from the list, then check.
The second feature of a shape is the number of peaks: how many separate piles are in the histogram? Most distributions have one peak. If you see two separate piles (a two-peaked distribution), most likely two different groups are mixed in one column. Think of a school bus stop where primary school students and high school students wait at the same stop. The histogram of their heights has two piles: around 120–135 cm and around 160–180 cm. The average height could be 150 cm, but nobody at the stop is 150 cm tall. In a two-peaked distribution the mean falls into the gap between the two peaks and describes no observation at all.
Example 2 (case): ad spend. In lesson 11 you saw two piles in the histogram of daily ad spend, and you found that they were two periods: with the campaign (January–April) and without it (May–June). Now let's look at what this shape does to the summary numbers:
import pandas as pd import matplotlib.pyplot as plt marketing = pd.read_csv("marketing.csv") spend = marketing["ad_spend"] fig, ax = plt.subplots() counts, edges, _ = ax.hist(spend, bins=15) ax.set_title("Daily ad spend") ax.set_xlabel("Ad spend ($)") ax.set_ylabel("Number of days") print(counts.astype(int).tolist()) print(round(spend.mean(), 1), spend.median())
Output[32, 28, 1, 0, 0, 1, 9, 14, 31, 21, 15, 12, 13, 3, 1]
157.1 193.0The first two bins hold 60 days (about $0–$47), then three bins are almost empty, and then the second pile starts. The mean is $157.1 and the median is $193. Both are misleading in this distribution: the mean falls right into the gap between the two piles, and the median falls on the edge of the bigger pile only because that pile has more days. The sentence "we spend $157 on a typical day" describes no day. Try it yourself: first draw the histogram, then split the data into before and after May 1 and print the mean of each part.
Try it now· not graded; doesn't affect progress
After the split, you get two distributions with one peak each: in the campaign period the mean of 120 days is $224.5, and afterward the mean of 61 days is $24.5. In each part the mean and the median are close to each other, so each part can be summarized on its own. When you see a two-peaked histogram, your first job is to ask "which two groups are mixed?" A column that names the group (date, device, category) is often already in the table.
Now we can turn the three questions into a decision. In lesson 14 you saw that the standard deviation is strongly affected by extreme values, and in lesson 15 you saw that the IQR is not. In lesson 12 you made the same distinction between the mean and the median. These two pairs go together:
| Shape | Center | Spread | Why |
|---|---|---|---|
| Symmetric, one peak | Mean | Standard deviation | No extreme values; the mean is right in the middle, and the std describes the typical distance well |
| Skewed, one peak | Median | IQR | The tail inflates the mean and the std; the median and the IQR are not affected by the tail |
| Two peaks | Split the groups first | Summarize each group by its own shape | One center describes no observation |
For amount, this means "median $44.95, IQR $61.60"; for delivery days, "mean 2.98 days, standard deviation 1.16 days". With skewed data you do not need to hide the mean completely: for a question about totals (a revenue forecast), as you saw in lesson 12, the mean is still the right tool. But for the question "what does a typical order look like?", the answer is the median and the IQR.
Match each variable with the summary to report.
For each row, pick its match from the list, then check.
Let's go back to the first question of the case: is a $200 Electronics order more unusual, or a $75 Books order? Looking at the amounts, the answer seems to be $200; but these two orders are not measured with the same ruler. In Electronics, $200 can be a normal amount, while in Books, $75 is very large. How unusual an observation is must be measured against the center and the spread of its own group.
Here is a familiar situation from school: you got 80 out of 100 on one exam and 17 out of 20 on another. Which one is better? The raw scores cannot be compared; the scales are different. You need to convert them to a common ruler. The z-score is that ruler: how many standard deviations an observation is away from the mean.
Outputz = (value − mean) / standard deviationThe numerator says how far the value is from the mean in its own unit ($, days, points); dividing by the standard deviation turns this distance into "how many typical distances." That is why a z-score has no unit, and why observations in different units and on different scales can be compared with z. You read two things:
Example 3 (case): two orders. Let's take the mean and the standard deviation of each category and calculate the z-scores of the two orders:
import pandas as pd orders = pd.read_csv("orders.csv") g = orders.groupby("category")["amount"].agg(["mean", "std"]) print(g.round(1)) electronics = g.loc["Electronics"] books = g.loc["Books"] print(round((200 - electronics["mean"]) / electronics["std"], 2)) print(round((75 - books["mean"]) / books["std"], 2))
Output mean std
category
Beauty 27.9 24.2
Books 21.8 15.6
Clothing 68.5 55.8
Electronics 146.5 179.9
Home & Living 93.1 87.7
0.3
3.42Electronics order: (200 − 146.48) / 179.90 = 0.30. It is a little above the mean, an ordinary order in its category. Books order: (75 − 21.80) / 15.56 = 3.42. It is 3.4 standard deviations above the Books mean; very unusual in its own category. The order that is smaller in dollars is much more extreme for its own group. The line g.loc["Books"] selects one row from the group table of lesson 7; books["mean"] and books["std"] are the two values in that row.
Below, look at the z-score of different amounts in the Books category. In the code, the mean and the standard deviation are written as numbers from the table above:
In the Books category, how do the z-score and the sentence change when the amount changes?
Pick a value; predict the output first, then look.
1amount = 752average = 21.83spread = 15.564z = (amount - average) / spread5if z >= 0:6 side = "above"7else:8 side = "below"9print("z =", round(z, 2))10print("That is", round(abs(z), 2), "standard deviations", side, "the Books average")
z = 3.42 That is 3.42 standard deviations above the Books average
Faded lines didn't run with this value. $15 is below the average, so z is negative (−0.44); $22.50 is very close to the average (0.04); $37.50 is one standard deviation above (1.01); $75 is more than three standard deviations above (3.42). The sign gives the direction and the size gives the distance. abs() gives the number without its sign; the sentence already says the direction in a word, so we wrote the distance without a sign.
A large z-score does not mean the record is wrong. A $75 Books order could be a bulk purchase by a school, or it could be a unit price entered by mistake. z only answers the question "how unusual is this observation in its own group?"; the decision "real or error?" needs a look at the record itself. You will make that decision in lesson 21, together with outliers.
There is a well-known rule for z-scores: if the distribution is bell-shaped (symmetric, one peak, dense in the middle), most observations are between −2 and 2, and about two thirds are between −1 and 1. The condition of this rule matters more than the rule itself: bell shape. In a skewed distribution these proportions do not hold.
Example 4 (case): where does the rule hold? Let's calculate the z-scores of delivery days and amount, and look at the share of values with |z| ≤ 1 and |z| ≤ 2. Delivery days are empty for canceled orders, so we first drop the empty values with dropna(). abs() removes the sign (|z|): −1.3 and 1.3 are at the same distance.
import pandas as pd orders = pd.read_csv("orders.csv") for name in ["delivery_days", "amount"]: x = orders[name].dropna() z = (x - x.mean()) / x.std() print(name, round((z.abs() <= 1).mean(), 3), round((z.abs() <= 2).mean(), 3), round(z.max(), 2), (z > 3).sum())
Outputdelivery_days 0.803 0.987 3.47 1
amount 0.918 0.963 8.14 23In delivery days, 80.3% of the orders are within one standard deviation and 98.7% are within two. The largest z is 3.47: the only order that arrived in 7 days. In amount, 91.8% are within one standard deviation: much more than the "two thirds" rule. The reason is the skew: a few giant orders in the tail inflate the standard deviation, and a band that wide takes in almost all of the small orders. The same tail leaves a mark at the other end too: the largest z is 8.14 and 23 orders have a z-score above 3. In a bell-shaped distribution a z above 3 is very rare; here there are 23 of them.
Another common misunderstanding is to treat the z-score as a percentile. z = 2 does not mean "2 percent" or "98 percent"; it means "two standard deviations above the mean." The share of values below an observation is told by the percentile from lesson 15, not by z. The link between z and percentile changes with the shape of the distribution: in amount and in delivery days, the share of values with |z| ≤ 1 came out different. You can roughly turn z into a percentile only in a bell-shaped distribution; you will see the rule for that with the normal model in lesson 26.
Try it now· not graded; doesn't affect progress
For age, the share comes out very close to two thirds (66.7%), because age is nearly symmetric with one peak. In amount it is 91.8%, and in delivery days 80.3%. The rule is an assumption about the distribution; when the assumption does not hold, the numbers do not hold either.
The most familiar use of the z-score is to compare different exams. Example 5 (outside the case): Elif got 78 in math; the class mean is 60 and the standard deviation is 12. She got 85 in physics; the class mean is 80 and the standard deviation is 5. Compared with her class, in which subject did she do better?
Elif got 78 in math (mean 60, standard deviation 12) and 85 in physics (mean 80, standard deviation 5). Compared with her class, in which subject did she do better?
math_z = (78 - 60) / 12
physics_z = (85 - 80) / 5
print(math_z, physics_z)Output1.5 1.0In raw scores, physics is ahead (85 > 78); but in physics the class got both higher and more tightly packed scores. A 5-point lead over the mean is one standard deviation in physics; an 18-point lead over the mean is 1.5 standard deviations in math. Elif reached a higher part of her class in math.
This section is not in the test. In the histogram of a right-skewed variable, most bars are squeezed against the left edge, and the details of the tail cannot be seen. In this case it helps to turn the horizontal axis into a log scale: equal distances show equal ratios, not equal differences (going from 10 to 100 has the same length as going from 100 to 1,000). You should also choose the bin edges with equal ratios; np.geomspace(5, 1000, 16) splits the range from 5 to 1,000 into 16 edges that grow by the same ratio at every step:
import pandas as pd import numpy as np import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") fig, ax = plt.subplots() counts, edges, _ = ax.hist(orders["amount"], bins=np.geomspace(5, 1000, 16)) ax.set_xscale("log") ax.set_xlabel("Amount ($, log scale)") print(counts.astype(int).tolist())
Output[8, 37, 69, 91, 71, 139, 121, 128, 75, 73, 33, 14, 16, 5, 5]On the log axis, the amounts form a roughly one-peaked and much more balanced pile: the peak is around $30–$85. This is a transformation; writing above the chart that the axis is log is a must, otherwise the reader will take equal intervals as equal differences.
Let's see how well the "two thirds" rule holds in variables close to a bell shape: customer age and the time spent on the checkout page.
import pandas as pd customers = pd.read_csv("customers.csv") sessions = pd.read_csv("sessions.csv") for name, x in [("age", customers["age"].dropna()), ("checkout", sessions["checkout_time_sec"].dropna())]: z = (x - x.mean()) / x.std() print(name, round(x.skew(), 2), round((z.abs() <= 1).mean(), 3), round((z.abs() <= 2).mean(), 3))
Outputage 0.28 0.667 0.975
checkout -0.04 0.662 0.959The skewness of both variables is close to zero; the share with |z| ≤ 1 is 66.7% and 66.2%, and the share with |z| ≤ 2 is 97.5% and 95.9%. The rule holds well in data that is close to a bell shape. Remember that the same code on amount gave 91.8%: this is why you look at the histogram before you use the rule.
Let's calculate the z-score of one value with the mean and the standard deviation of the column itself:
import pandas as pd orders = pd.read_csv("orders.csv") x = orders["delivery_days"].dropna() print((x.mean(), 2), (x.std(), 2)) (((7 - x.mean()) / x.std(), 2))
Choosing a summary without looking at the shape. The sentence in the marketing report was this:
OutputOur average daily ad spend is $157.11.The calculation is correct, and the sentence is misleading. The histogram shows two piles: about $225 a day in the campaign period and about $25 a day afterward. Almost no day had spend close to $157. The mean falls into the gap between the two peaks. A correct report separates the periods: "From January to April we spent $224.49 a day on average, and from May to June we spent $24.55."
The second common mistake is to use the rule "mean ± 1 standard deviation covers two thirds of the data" on skewed data. For amount, this band falls between −$25.69 and $176.75: the lower limit is a negative amount (meaningless), and the band covers not two thirds but 91.8% of the orders. The rule needs a bell shape.
skew() is positive; a two-peaked histogram often shows two mixed groups, and a single mean describes no observation.Next lesson: You can now see a distribution, summarize it, and place an observation inside it. Next: which chart for which question, and how charts can mislead.
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.
Output2.98 1.16
3.47The order that arrived in 7 days is 3.47 standard deviations above the mean. In a nearly symmetric distribution this is a very rare distance; out of 851 deliveries, only this one is above z = 3. In amount there were 23 orders above the same distance: in a skewed distribution "z > 3" is seen much more often, and by itself it is not a reason for alarm.