…
…
Statistics and Data Analysis Fundamentals · Lesson 11 / 44 · Distribution and center
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.
Bazaar management has a new question: "How big are our orders, usually?" It is easy to quote an average right away, but the amounts of 885 orders can be very different from each other, and one number hides those differences. In this lesson you will see how all the amounts are distributed, with a table and a chart, before you give any single number.
By the end of the lesson you will draw the chart below yourself and write a three-sentence description under it:
OutputCenter: Most orders are under $100; the busiest bin is the leftmost one, about $5.81 to $35.61.
Spread: Amounts run from $5.81 to $899.90; the range is very wide.
Shape: There is a big pile on the left and a long tail on the right made of a few large orders.In this lesson you will:
In lesson 4 you used describe() to see the smallest value, the largest value, and the mean of the amount column. Those numbers are useful, but they do not show one thing: where the values pile up. Imagine two columns with the same mean. In one, all orders are around $75. In the other, most are around $25 and a few are $500. The mean can come out the same in both, but these two stores do not look alike at all.
In 1973 the statistician Francis Anscombe showed this with a striking example: he made four small data sets with almost the same means and the same spread. Someone who looked only at the summary numbers would think the four were the same. When the charts were drawn, one was a straight line, one was a curve, and in one a single outlier decided everything. The lesson was clear: see the data before you move on to summary numbers.
The list of which values a variable takes, and how often, is called its distribution. For a categorical variable, seeing the distribution is easy: value_counts() from lesson 4 counts how many rows each category has. But in a continuous number like amount, almost every value is different. Among 885 orders there are hundreds of different amounts, and value_counts() gives you a list of hundreds of rows with 1 or 2 in each. The solution is to split the values into intervals and count how many values fall into each one. The table of these counts is called a frequency table.
In pandas, the function that splits values into intervals is pd.cut. The first argument is the column, and bins holds the interval edges. The result is a new column that shows which interval each row falls into; you count it with value_counts(). To list the intervals in their own order, you add sort_index() at the end (we did the same for the month counts in lesson 6).
import pandas as pd orders = pd.read_csv("orders.csv") edges = [0, 25, 50, 100, 250, 1000] print(pd.cut(orders["amount"], bins=edges).value_counts().sort_index())
Outputamount
(0, 25] 241
(25, 50] 258
(50, 100] 203
(100, 250] 148
(250, 1000] 35
Name: count, dtype: int64Learn to read the interval notation: (25, 50] means "greater than 25, and less than or equal to 50". A round bracket says the edge is not included, and a square bracket says it is included. This way an order of exactly $50 does not fall into two intervals at once; it is counted only in (25, 50].
Now read the table. 241 + 258 + 203 + 148 + 35 = 885: every order is in one interval and only one. The first three intervals, up to $100, hold 702 orders, which is about 79%. Only 35 orders are above $250. Before you draw any chart, you can already say "most orders are small, and a few are very large".
Notice the widths of the intervals: the first two are $25 wide, the third is $50, the fourth is $150, and the last is $750. Unequal edges like these are useful for groups in business language such as "small / medium / large order", but they make the shape harder to read: a wide interval can collect more values just because it is wide. This is why the histogram you will draw soon uses intervals of equal width. Change the edges and see for yourself how the table changes:
Try it now· not graded; doesn't affect progress
A frequency table describes with numbers; a histogram describes the same thing with a picture. The range of values is split into bins of equal width. One bar is drawn for each bin, and the height of the bar is the number of observations that fall into that bin. The horizontal axis shows the value (here the amount, in $), and the vertical axis shows the count (the number of orders).
Get two points clear from the start, because most confusion comes from here:
1. A bar is not one order. A bar is the count of all the orders in an interval. In the chart at the start of the lesson, the leftmost bar stands for 350 orders at once.
2. Height is not value. A tall bar does not say that those orders are expensive; it says that there are many orders in that interval. The expensive orders are on the right of the chart; you read how expensive they are from the horizontal axis.
A histogram looks like a bar chart, but it is not the same thing. In a bar chart the horizontal axis holds categories (Electronics, Clothing, Books...) and their order can be changed. In a histogram the horizontal axis is a continuous number axis; the bars touch each other, because where one interval ends the next one starts, and their order cannot be changed. You will see bar charts for categorical variables separately in lesson 17.
In the amount histogram at the start of the lesson, the tallest bar is on the far left, at about $5.81–$35.61, with a height of 350. What does this bar say?
The basic library for charts in Python is matplotlib. When you import it, the usual name is plt: import matplotlib.pyplot as plt. Every chart starts with two parts: a figure (fig, the canvas) and a drawing area on it (ax, the frame). The line that gives you both together is the same in every chart: fig, ax = plt.subplots(). Then you draw and add labels with the methods of ax:
| Method | What it does |
|---|---|
ax.hist(data, bins=30) | Draws a histogram with 30 bins |
ax.set_title("...") | The title of the chart |
ax.set_xlabel("...") | The name of the horizontal axis |
ax.set_ylabel("...") | The name of the vertical axis |
On this platform, a chart appears under the output by itself when the code finishes. When you work on your own computer, you need to write plt.show() at the end.
ax.hist does not only draw the chart; it also returns three things: the counts in each bin (n), the bin edges (edges), and the bars that were drawn. The first two are the numeric version of the chart; when you cannot read the chart by eye, you look at them. We have no use for the third in this lesson; in Python it is a habit to assign an unused value to the name _.
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") fig, ax = plt.subplots() n, edges, _ = ax.hist(orders["amount"], bins=30) ax.set_title("Distribution of order amounts") ax.set_xlabel("Amount ($)") ax.set_ylabel("Number of orders") print(n[:5].astype(int).tolist()) print(edges[:3].round(1).tolist())
Output[350, 261, 90, 57, 20]
[5.8, 35.6, 65.4]n is a NumPy array; its numbers are stored as floats, so we turned them into integers with astype(int) and into a list with tolist(). The first bin starts at $5.81 (the smallest order) and goes up to $35.61. Each of the 30 bins is about $29.80 wide, because matplotlib splits the space between the smallest and the largest value into 30 equal parts. The first two bins hold 611 orders, and the next bins empty out quickly.
The short way to find the busiest bin also goes through n: n.max() gives the height of the tallest bar, and n.argmax() gives which bin that bar is (counting from 0). The lower edge of that bin is edges[n.argmax()]. In the amount histogram, n.argmax() is 0; the busiest bin is the leftmost one.
Writing the unit in the axis names is a small but important habit: "Amount ($)" instead of "Amount". The manager who sees the chart will not see your code; the chart has to be understood on its own. In a chart with no title and with axis names that have no units, the reader has to guess what is counted and in which unit it is measured.
Put the lines that draw the amount histogram 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
Now run the same histogram yourself and change it:
Try it now· not graded; doesn't affect progress
The shape of a histogram looks like a fixed property of the data, but it is not: you choose the number of bins, and the choice changes the picture. Too few bins hide detail; all the orders pile up in one or two bars. Too many bins produce noise; only a few orders fall into each bin, the bars go up and down at random, and the picture turns into a toothed comb. In the amount column, if you choose 5 bins, 817 orders gather in the first bar and almost everything is in one bar; with 30 bins the first two bars are 350 and 261; with 200 bins most of the bars stay empty.
The block below has a sample of 60 orders (picked at random from Bazaar's amount column). Instead of drawing a chart, the code uses np.histogram to do the same counting: it gives the same counts that ax.hist returns, without drawing. Change the number of bins and look at the counts in the first six bins and at how many bins stay empty:
Change the number of bins: how are the same 60 amounts spread over the bins, and how many bins stay empty?
Pick a value; predict the output first, then look.
1import numpy as np2bin_count = 53amounts = [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]9n, edges = np.histogram(amounts, bins=bin_count)10print("First six bins:", n[:6].tolist())11print("Empty bins:", int((n == 0).sum()), "/", bin_count)
First six bins: [50, 7, 2, 0, 1] Empty bins: 1 / 5
Faded lines didn't run with this value. With 5 bins, 50 of the 60 orders are in the first bar: the detail is lost. With 30 bins, the first two bins have 19 orders each, and then the counts drop quickly. With 200 bins, 172 of the bins are empty and the filled ones hold 1–6 orders: the ups and downs you see come from the bins being too narrow, not from the data. The interpretation "most orders are on the left, with a long tail on the right" is true with all three choices; do not trust an interpretation that shows up with only one bin count.
The rule that comes out of this is simple: state an interpretation only if it still holds with several bin counts. The sentence "most orders are small, and there is a long tail on the right" is valid with 5, 30, and 200 bins; so it belongs to the data. If an observation like "there is a second peak around $100 in the chart" shows up with only one bin count and disappears with the others, that peak most likely comes from your choice and not from the data.
If you do not give bins, matplotlib uses 10 bins. This is often a good start, but it is not a sacred number. A good habit in practice: first draw with the default, then cut the number of bins in half and double it; write down what stays the same in all three pictures. You can also define the bins with edges instead of a number: bins=range(0, 101, 10) builds the bins 0–10, 10–20, ..., 90–100. Giving the edges yourself makes reading easier, because it places the bins on round numbers.
You drew the histogram; now you need to describe it in words. It is not enough to say "here is the chart" to a manager and leave; you need to put into a sentence what the chart says. For this, ask the same three questions every time:
1. Center: Where do most values pile up? (In which interval are there the most observations?)
2. Spread: How wide an area do the values cover? (How far does it reach from the smallest to the largest, is the pile narrow or wide?)
3. Shape: Is the pile in the middle or leaning to one side? Does it go down evenly on both sides, or is there a long tail on one side? Is there a single peak, or are there two separate piles?
These three questions are the skeleton of this unit. In this lesson you answer them in words; in the next lessons you will turn each one into a number: the center with the mean and the median, the spread with the standard deviation and the quartiles, and the shape with skewness and the z-score.
We have already described the amount distribution: the center is on the left (the busiest interval is $5.81–$35.61), the spread is very wide (from $5.81 to $899.90), and the shape is a tail stretching to the right. Now let's look at a variable in Bazaar that looks completely different: delivery time. Delivery days are integers from 1 to 7, so we want one bin for each day. When you write bins=7, range=(0.5, 7.5), the bins become 0.5–1.5, 1.5–2.5, ... and each integer sits in the middle of its own bin. The delivery day is empty for canceled orders, so first we remove the blanks with dropna() (the opposite of isna() from lesson 4: it keeps the values that are not empty).
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") fig, ax = plt.subplots() n, edges, _ = ax.hist(orders["delivery_days"].dropna(), bins=7, range=(0.5, 7.5)) ax.set_title("Distribution of delivery time") ax.set_xlabel("Delivery time (days)") ax.set_ylabel("Number of orders") print(n.astype(int).tolist())
Output[87, 212, 275, 196, 70, 10, 1]With the three questions: the center is at 3 days (275 orders, the tallest bar); the spread is from 1 to 7 days, but the great majority of orders are in the 2–4 day range; the shape has a single peak, and on both sides of the peak the bars go down in a similar way (212 at 2 days, 196 at 4 days). There are a few orders at 6 and 7 days on the right, but there is no long tail like the one in amount. Compare with amount: there, the pile was on the far left and there was a very long tail to the right.
Learn a third shape too: two separate piles. In the histogram of Bazaar's daily ad spend, some of the days gather around $0–$50 and some around $150–$300, with almost no days in between. A histogram with two peaks often shows that two different groups are mixed together. In the example at the end of this lesson, you will find out what these two groups are.
Match each description in words with the variable it fits in Bazaar.
For each row, pick its match from the list, then check.
Pay attention to two things when you write a description. The first is: do not claim something that is not in the chart. The amount histogram does not say which product sells the most, in which month the orders were placed, or why customers place large orders; it only says how the amounts are distributed. The second is: put a number or an interval name in the sentence. Writing "most orders are under $100" instead of "most orders are small" lets the reader understand how small.
A histogram is not only for store data; for any numeric variable you ask the same questions. Think of the exam scores of a class of 30 students. The teacher asks, "How did the class do?" We wrote the scores by hand into a list:
import matplotlib.pyplot as plt scores = [72, 65, 81, 78, 12, 69, 74, 85, 63, 77, 70, 80, 66, 73, 18, 79, 68, 75, 82, 71, 64, 76, 60, 83, 67, 74, 79, 70, 62, 84] fig, ax = plt.subplots() n, edges, _ = ax.hist(scores, bins=range(0, 101, 10)) ax.set_title("Distribution of exam scores (30 students)") ax.set_xlabel("Score (out of 100)") ax.set_ylabel("Number of students") print(n.astype(int).tolist())
Output[0, 2, 0, 0, 0, 0, 9, 13, 6, 0]The bins are 0–10, 10–20, ..., 90–100. With the three questions: the center is in the 70–80 range (13 students); for the spread, the great majority of students (28 people) are between 60 and 90, but the scores run from 12 to 85; the shape is a single pile between 60 and 90, with two students (12 and 18) cut off on the left. These two scores are not a part of the pile; they may tell a separate story (arriving late to the exam, a wrong paper). The histogram made them visible; the mean would mix these two scores with the others and show the class a little lower than it is. You will see what to do with outliers in lesson 21; for now, "see and say" is enough.
Try it now· not graded; doesn't affect progress
The same three questions work in other places too: the distribution of ride times on a bus line, the daily minutes of use of an app, the finishing times in a marathon. In each one, you first draw the histogram, and then you ask "where are most values, how spread out are they, is there a tail?" If you can put the answer into one sentence, you have understood the distribution.
In the histogram of ad spend we saw two separate piles. In a histogram with two peaks, the first job is to check whether the peaks disappear when the number of bins changes; if they stay, you ask whether two groups are mixed. Let's set the bins first to 10 and then to 4 and look at the counts:
import pandas as pd import numpy as np mkt = pd.read_csv("marketing.csv") print(np.histogram(mkt["ad_spend"], bins=10)[0].tolist()) print(np.histogram(mkt["ad_spend"], bins=4)[0].tolist()) mkt["month"] = pd.to_datetime(mkt["date"]).dt.month print(mkt.groupby("month")["ad_spend"].mean().round(0))
Output[53, 8, 0, 1, 18, 36, 29, 19, 14, 3]
[61, 19, 76, 25]
month
1 227.0
2 226.0
3 217.0
4 228.0
5 26.0
6 23.0
Name: ad_spend, dtype: float64With 10 bins the two piles are clearly visible (53 days on the left, a peak of 18–36 on the right); even with 4 bins, the dip in the second bin can be seen. The peaks do not come from the choice of bins. The average by month shows the reason: in January–April, more than $215 was spent per day on average, and in May and June less than $27. The ad campaign ended at the end of April; the two piles in the histogram are a mix of two periods, with a campaign and without one. Summarizing these two periods with a single "average ad spend" would describe both of them wrongly.
Because the delivery day is an integer, there is no need to split it into intervals; each value can be counted on its own row. To see the shares side by side, we put the two counts in one table:
Getting the frequency table with value_counts() and forgetting to add sort_index():
Outputprint(orders["delivery_days"].value_counts())
delivery_days
3.0 275
2.0 212
4.0 196
1.0 87
5.0 70
6.0 10
7.0 1The result of value_counts() lists values from the most frequent to the rarest. This order answers the question "which value is the most frequent?" but it loses the shape of the distribution: someone who looks at the order 3, 2, 4, 1, 5 cannot see that the peak is in the middle and that it goes down evenly on both sides. For a distribution you need the values in their own order: orders["delivery_days"].value_counts().sort_index() gives 87, 212, 275, 196, 70, 10, 1 for 1, 2, 3, 4, 5, 6, 7, and the shape is visible at once. The same rule applies to an interval table built with pd.cut.
pd.cut and count with value_counts().sort_index(), you get a frequency table.fig, ax = plt.subplots() and ax.hist(data, bins=...); the bar height is the number of observations in the interval, and every chart has a title and axis names with units.Next lesson: We answered "Where are most orders?" in words; now we will answer it with a single number: the mean and the median, and which one is more honest in a distribution with a tail such as amount.
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.
import pandas as pd orders = pd.read_csv("orders.csv") days = orders["delivery_days"].dropna() table = pd.DataFrame({ "orders": days.value_counts().sort_index(), "share": days.value_counts(normalize=True).sort_index().round(3), }) print(table.rename_axis(None))
Output orders share
1.0 87 0.102
2.0 212 0.249
3.0 275 0.323
4.0 196 0.230
5.0 70 0.082
6.0 10 0.012
7.0 1 0.001Of the 851 delivered orders, 32.3% arrived in 3 days; 2, 3, and 4 days together are about 80% of the orders. rename_axis(None) removes the index name line above the table and makes the table simpler. The days look like 1.0, 2.0 with decimals, because the column had empty values and pandas keeps a numeric column with empty values as float.