…
…
Statistics and Data Analysis Fundamentals · Lesson 8 / 44 · Grouping and merging
PreviewIn this lesson you will
pivot_table and crosstabYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In lesson 7 you looked at the drop by month, by device, and by category, one at a time: orders fell in May, and mobile brings more orders than desktop. But the manager's real question needs both at once: "Which device drove the May drop?" In this lesson you will build the two breakdowns in one table, and then turn the counts into proportions in the right direction.
By the end of this lesson you will have built this table and written the sentence under it yourself:
Outputdevice desktop mobile
month
1 0.422 0.578
2 0.412 0.588
3 0.335 0.665
4 0.401 0.599
5 0.500 0.500
6 0.490 0.510
Sentence: "From January to April, 58% to 67% of orders each month came from mobile; in May and June it fell to half."A one-way table answers one question: "How many orders per month?" or "How many orders per device?" Real analysis questions often ask about two variables together: "How many orders per month, per device?" In this kind of table, the rows hold the values of one variable and the columns hold the values of the other. Each cell summarizes the small group where the two meet. It is the fastest way to see whether the behavior of one variable changes with the other.
In this lesson you will:
pivot_table in one call, and put counts, sums, or means in the cells.crosstab, and add a totals row.In lesson 7 you used the groupby pattern with one column: df.groupby("device").size() gave the number of orders on each device. groupby also accepts a list. df.groupby(["month", "device"]).size() counts each month and device combination as its own group. The result has a two-level index: month on the outside, device on the inside.
Example 1 (case): Month and device
import pandas as pd df = pd.read_csv("orders.csv") df["month"] = pd.to_datetime(df["date"]).dt.month print(df.groupby(["month", "device"]).size().head(4)) print(df.groupby(["month", "device"]).size().unstack())
Outputmonth device
1 desktop 65
mobile 89
2 desktop 73
mobile 104
dtype: int64
device desktop mobile
month
1 65 89
2 73 104
3 59 117
4 65 97
5 56 56
6 51 53The first output is a long list: 6 months × 2 devices = 12 rows, hard to scan. unstack() moved the inner level (device) into the columns and turned the list into a table. Now you can see it at a glance: desktop stays between 51 and 73 orders every month, but mobile dropped from 117 in March to 56 in May. In the month-by-device table, mobile's sharp fall in May is easy to spot. Most of the drop is on mobile.
This job is so common that pandas has a ready-made method for it: pivot_table. If you have used pivot tables in Excel, the idea will feel familiar. It takes four arguments: index (the column that goes to the rows), columns (the column that goes to the columns), values (the column to summarize in the cells), and aggfunc (the summary function: "count", "sum", "mean", and so on). The table in Example 1 can be written in one call: df.pivot_table(index="month", columns="device", values="order_id", aggfunc="count"). Counting order numbers is counting orders.
What you gain over a groupby chain is readability: the argument names say which variable goes where. Put the parts of the pivot call in the right order.
Put the pivot call that gives the number of orders for each month and device in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
A cell can hold a sum instead of a count. Let's print revenue by month and category, in thousands of dollars. Dividing big numbers by a thousand and rounding makes the table easier to read.
Example 2 (case): Revenue by month and category
import pandas as pd df = pd.read_csv("orders.csv") df["month"] = pd.to_datetime(df["date"]).dt.month t = df.pivot_table(index="month", columns="category", values="amount", aggfunc="sum") print((t / 1000).round(2))
Outputcategory Beauty Books Clothing Electronics Home & Living
month
1 0.53 0.51 2.93 3.37 4.06
2 0.67 0.41 3.62 6.57 4.39
3 0.77 0.43 4.08 5.00 2.98
4 0.83 0.58 3.35 3.58 3.47
5 0.52 0.37 2.42 2.87 2.48
6 0.52 0.25 1.83 1.47 1.97Electronics revenue went from $6.57 thousand in February to $1.47 thousand in June, while Beauty stayed in a narrow range. As in lesson 7, this revenue covers all orders, including returned and canceled ones.
Two extra options are often useful. margins=True adds row and column totals under the name All. If a combination has no orders at all, the cell stays empty (NaN); fill_value=0 fills empty cells with zero. Try it yourself:
Try it now· not graded; doesn't affect progress
In the second step of "Try", the table did not give an error when you deleted aggfunc; the cells turned into something else. Predict what happens before you run it.
What ends up in the cells if you do not write aggfunc in a pivot_table call?
This trap is silent: the code runs, the table looks fine, and only the numbers answer the wrong question.
import pandas as pd df = pd.read_csv("orders.csv") df["month"] = pd.to_datetime(df["date"]).dt.month print(df.pivot_table(index="month", columns="device", values="amount").round(1))
Outputdevice desktop mobile
month
1 76.2 72.4
2 107.0 75.6
3 94.2 65.8
4 90.9 60.8
5 78.0 76.7
6 53.5 62.5If you presented this as "monthly revenue", you would be saying that Bazaar sold only about $75 in a month. Real monthly revenue is in the thousands of dollars. Checking the size of the numbers is the easiest way to catch this mistake: monthly revenue cannot be as small as the amount of one order.
If both variables are categorical and you only ask how many times they appear together, there is a shorter tool: pd.crosstab(row_column, column_column). This table is called a crosstab (also known as a contingency table). crosstab is not a DataFrame method but a pandas function; it takes the two columns directly as arguments and does not ask for values or aggfunc, because its job is counting.
Let's start with a small table you can check by hand. A school has recorded the class and the club of five students.
Example 3 (not the case): Class and club
import pandas as pd t = pd.DataFrame({ "class": ["9A", "9A", "9B", "9B", "9B"], "club": ["robotics", "music", "music", "music", "robotics"], }) print(pd.crosstab(t["class"], t["club"]))
Outputclub music robotics
class
9A 1 1
9B 2 1Count the list by hand: in 9A there is one robotics and one music student; in 9B there are two music and one robotics. Each cell shows how many times a class-club combination appears. The columns are in alphabetical order. Now let's count device and order status at Bazaar; margins=True adds the totals here too.
Example 4 (case): Device and status
import pandas as pd df = pd.read_csv("orders.csv") print(pd.crosstab(df["device"], df["status"], margins=True))
Outputstatus canceled completed returned All
device
desktop 15 331 23 369
mobile 19 456 41 516
All 34 787 64 885There are 41 returns on mobile and 23 on desktop. What follows from these numbers?
There are 41 returns on mobile and 23 on desktop. Which sentence is correct?
This is the same as the within-group rate in lesson 7: to compare, you divide each group by its own size. crosstab does this in one step with the normalize argument, and it has two directions. See which direction completes which totals to 1 on the club table.
Change the normalize direction: which totals become 1?
Pick a value; predict the output first, then look.
1import pandas as pd23t = pd.DataFrame({"class": ["9A", "9A", "9B", "9B", "9B"], "club": ["robotics", "music", "music", "music", "robotics"]})4direction = "index"5print(pd.crosstab(t["class"], t["club"], normalize=direction).round(2))
club music robotics class 9A 0.50 0.50 9B 0.67 0.33
Faded lines didn't run with this value. "index" makes each row (each class) add up to 1 on its own: 2 of the 3 students in 9B are in music, 0.67. "columns" makes each column (each club) add up to 1: 2 of the 3 music members are from 9B, again 0.67, but this time the sentence is different. The 9A music cell changed from 0.50 to 0.33 because the denominator changed: instead of the 2 students of 9A, it is the 3 members of music.
normalize="index" makes each row add up to 100% on its own: the cell answers "of the people in this row, how many are in this column?" normalize="columns" makes each column add up to 100%: the cell answers "of the people in this column, how many are in this row?" Both tables hold the same counts; the only thing that changes is the denominator. The way to know which one to choose is to write the question as a sentence.
Example 5 (case): Three proportion tables
import pandas as pd df = pd.read_csv("orders.csv") df["month"] = pd.to_datetime(df["date"]).dt.month print(pd.crosstab(df["device"], df["status"], normalize="index").round(3)) print(pd.crosstab(df["device"], df["status"], normalize="columns").round(3)) print(pd.crosstab(df["month"], df["device"], normalize="index").round(3))
Outputstatus canceled completed returned
device
desktop 0.041 0.897 0.062
mobile 0.037 0.884 0.079
status canceled completed returned
device
desktop 0.441 0.421 0.359
mobile 0.559 0.579 0.641
device desktop mobile
month
1 0.422 0.578
2 0.412 0.588
3 0.335 0.665
4 0.401 0.599
5 0.500 0.500
6 0.490 0.510In the first table every row adds up to 1: 7.9% of mobile orders and 6.2% of desktop orders were returned. In the second table every column adds up to 1: 64.1% of returns came from mobile. These two numbers (0.079 and 0.641) come from the same 41 returns but answer different questions. The 64.1% looks alarming at first; but mobile already brings 58% of all orders, so its slightly high share of returns is just another view of the 1.7-point gap in return rates.
The third table is the target output of this lesson. Because each month is completed to 1 on its own, the size of the month (154 or 104 orders) does not distort the comparison. From January to April, mobile's share is between 0.578 and 0.665; in May and June it is 0.500 and 0.510. The sentence for the manager: "From January to April, 58% to 67% of orders each month came from mobile; in May and June it fell to half." This table does not tell you the number of mobile orders; the count table in Example 1 does. Match each question with the table it needs.
Match each question with the table that answers it.
For each row, pick its match from the list, then check.
The most common mistake is to say a number from one direction with the sentence of the other. Try a presentation scenario with the category × device table.
The category × device table has two numbers: in the row proportions, the mobile cell of the Clothing row is 0.805; in the column proportions, the Clothing cell of the mobile column is 0.415. The manager wants to present "Clothing is 80% of mobile." What do you say?
Pick an option and see what happens. There are no points; you can try the other options too.
Row proportions are also the basic tool for checking whether two categorical variables are related. In Bazaar's customer survey (survey.csv, 300 responses), each response has the carrier that delivered the order and a satisfaction score from 1 to 5. Let's look at how the scores are spread for each carrier. Because the carriers received different numbers of responses, we use row proportions instead of raw counts.
Example 6 (case): Carrier and satisfaction
import pandas as pd a = pd.read_csv("survey.csv") print(pd.crosstab(a["carrier"], a["satisfaction"], normalize="index").round(2)) print(a["carrier"].value_counts().sort_index())
Outputsatisfaction 2 3 4 5
carrier
Arrow Express 0.03 0.15 0.42 0.40
Caravan Freight 0.08 0.36 0.39 0.18
Gull Post 0.04 0.27 0.54 0.14
carrier
Arrow Express 130
Caravan Freight 80
Gull Post 90
Name: count, dtype: int64Of the people who received their order from Arrow, 40% gave a 5; of those who received it from Caravan, only 18%. There is a clear difference between the rows: carrier and satisfaction change together. But remember the distinction from lesson 3: this is a survey, so it is observational data. We did not assign the carrier to customers at random; maybe Caravan goes to farther cities or carries bigger packages. This table does not let you say "Caravan causes dissatisfaction"; it lets you say "satisfaction is lower among respondents who received their order from Caravan." In lesson 34 you will test with a chi-square test whether this difference could have happened by chance.
Try it now· not graded; doesn't affect progress
In lesson 7 you found the return rate for each category with groupby. The same question, with a row-proportion crosstab, shows all statuses together.
import pandas as pd df = pd.read_csv("orders.csv") print(pd.crosstab(df["category"], df["status"], normalize="index").round(3))
Outputstatus canceled completed returned
category
Beauty 0.065 0.899 0.036
Books 0.060 0.923 0.017
Clothing 0.030 0.801 0.169
Electronics 0.019 0.949 0.032
Home & Living 0.034 0.933 0.03416.9% of Clothing orders were returned; in the other four categories the rate is below 4%. Each row adds up to 1 because the question is "what percent of each category's orders ...".
A university asked 12 students how they get to campus. The same count table gives two different percentages.
import pandas as pd a = pd.DataFrame({ "faculty": ["Engineering"] * 5 + ["Science"] * 4 + ["Economics"] * 3, "transport": ["metro", "metro", "bus", "metro", "walk", , , , , , , ], }) (pd.crosstab(a[], a[], margins=)) (pd.crosstab(a[], a[], normalize=).(2))
Forgetting `aggfunc`. If you write df.pivot_table(index="month", columns="device", values="amount") for a "monthly revenue" table, you see numbers between 50 and 110 in the cells: these are not totals but average basket amounts. If you want a total, write aggfunc="sum"; if you want a count, write aggfunc="count", and check the size of the result with common sense. In older code you may also see a method called pivot that does not summarize; it gives an error when the same month-device combination has more than one row, so use pivot_table in analysis.
pivot_table(index=..., columns=..., values=..., aggfunc=...) summarizes two breakdowns in one table; the default summary is the mean, so write aggfunc explicitly for a sum or a count; margins=True adds totals and fill_value=0 fills empty cells.pd.crosstab(row, column) gives the number of times two categorical variables appear together; when the groups have different sizes, raw counts are not enough to compare, and you need proportions.normalize="index" completes each row to 1 and normalize="columns" completes each column to 1; the percentage is inside whichever group is the subject of the sentence, and the two directions answer different questions. A difference in observational data does not show cause and effect.Next lesson: The orders table has no cost and no customer city; that information sits in other tables. Next up is joining tables.
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.
Outputtransport bus metro walk All
faculty
Economics 1 2 0 3
Engineering 1 3 1 5
Science 2 1 1 4
All 4 6 2 12
transport bus metro walk
faculty
Economics 0.33 0.67 0.00
Engineering 0.20 0.60 0.20
Science 0.50 0.25 0.2560% of Engineering students come by metro (3 / 5, a row proportion). Half of the people who come by metro are from Engineering (3 / 6, a column proportion). The rows are in alphabetical order, so Economics comes first; the order of the rows does not rank anything. The proportions do.