Group Comparisons
Learning Objectives
- You can calculate one total or mean per category.
- You can sort grouped results and distinguish them from sorted individual records.
- You can use group counts to explain what a comparison summarizes.
- You can select individual observations before calculating their grouped results.
The previous chapter calculated one total for a requested subject. This chapter prepares comparisons across subjects: one row per category, containing its total, mean, or observation count. Pandas provides a grouping operation for the category summaries we built with dictionaries in Part 4.
One Total per Subject
Continue in data-analysis with the original sessions.csv. Replace analysis.py with:
import pandas as pd
sessions = pd.read_csv("sessions.csv")subject_totals = sessions.groupby("subject", as_index=False)["minutes"].sum()print(subject_totals)The output is:
subject minutes0 Languages 1001 Mathematics 3152 Programming 3503 Writing 150groupby("subject", as_index=False) groups rows that have the same subject. ["minutes"] chooses the measurement to summarize, and sum() adds the values in each group. The result has one row per subject instead of one row per session.
as_index=False keeps the subject names in an ordinary column of the result. We can therefore continue to use the named columns subject and minutes. The minutes column now contains totals; it no longer contains individual session lengths.
There is one result row for each category present in the input. If the input has no rows, there are no groups: the result still has the columns subject and minutes, but no rows. It does not create a category containing a zero total.
The diagram follows the Programming records. Their durations contribute to one result even though the records appear in different positions in the original table.
Grouping connects sessions with the same subject to one calculated total.
Sorting the Summary
Replace the final print(subject_totals) line with:
subject_totals = subject_totals.sort_values("minutes", ascending=False)print(subject_totals)The largest total now comes first:
subject minutes2 Programming 3501 Mathematics 3153 Writing 1500 Languages 100sort_values orders rows using the named column. ascending=False selects descending order, from largest to smallest. The returned table keeps its index labels, so the labels do not become 0, 1, 2, 3 in the new order.
Sorting the original sessions would instead order individual durations. Its first row would be the 110-minute Writing session. The grouped result answers a different question: Programming has the greatest total, even though Writing contains the longest individual session.
Practise grouping and sorting by making one small change in each supplied Python program. Follow how each change chooses the groups, the measurement, or the order of the result.
Now consider what the grouped rows represent when a summary is sorted.
Ordering Two Tables
0 / 5 points
A table contains these room sessions:
| Room | Minutes |
|---|---|
| A | 40 |
| B | 35 |
| A | 10 |
| B | 30 |
Compare two operations:
- Sort the individual records by minutes, largest first.
- Calculate total minutes for each room, then sort those totals, largest first.
Which room appears first in each result?
Apply grouping and sorting to the room bookings in the following exercise. A room can appear in several records, just as a subject can appear in several sessions.
Total Booking Time by Room
0 / 30 points
Complete room_totals(bookings). Return one row per room with its total booking duration, sorted from largest total to smallest. Use exactly the columns room and minutes, in that order.
For bookings A: 20, B: 40, and A: 30, the result has A: 50 followed by B: 40. Tied rooms may appear in either order; result index labels do not matter.
Room names and numeric durations have no missing values. An empty input returns the two result columns with no rows. Leave bookings unchanged.
Comparing Totals and Averages
To compare average session lengths, calculate a mean for each group. Add these lines to analysis.py:
subject_means = sessions.groupby("subject", as_index=False)["minutes"].mean()subject_means = subject_means.sort_values("minutes", ascending=False)print(subject_means)Mathematics now comes first with a mean of 52.5 minutes, ahead of Programming’s 35 minutes. Programming has the greater total because its ten sessions contribute more recorded time than the six Mathematics sessions. Use a sum to compare total recorded time and a mean to compare average session lengths.
Comparing Two Summaries
0 / 5 points
These records contain four room sessions:
| Room | Minutes |
|---|---|
| A | 15 |
| A | 15 |
| A | 15 |
| B | 30 |
Which statement correctly compares total time and mean session length?
Counting Sessions per Subject
To calculate the number of observations behind each comparison, use size() on the groups. Add:
session_counts = sessions.groupby("subject", as_index=False).size()print(session_counts)These lines print:
subject size0 Languages 51 Mathematics 62 Programming 103 Writing 3The size column counts rows in each group. These counts show how many observations each mean summarizes; they do not establish that the observations represent all studying for that subject.
With no input observations, this summary has no rows and keeps its result columns, subject and size.
The following exercise focuses on the counts; its result rows may appear in any order. Two sessions with identical values still count as two observations, and their durations do not affect the count.
Session Counts by Subject
0 / 20 points
Complete session_counts(sessions). Return one row per subject, with the columns subject and size in that order. The size value is the number of sessions recorded for that subject.
The result rows may appear in any order. Count every row, including repeated rows and sessions whose recorded duration is zero. Durations do not affect the count. Leave sessions unchanged. Subject names are present. For an empty input table, return an empty table with the two result columns.
Selecting Before Grouping
Sometimes a comparison concerns only certain observations. To compare recorded time in sessions lasting at least 40 minutes, select those sessions before calculating the subject totals:
mask = sessions["minutes"] >= 40long_sessions = sessions[mask]long_totals = long_sessions.groupby("subject", as_index=False)["minutes"].sum()print(long_totals)The result is:
subject minutes0 Mathematics 3151 Programming 1752 Writing 110No Languages session lasts at least 40 minutes, so that subject has no row in this result. Filtering subject_totals for totals of at least 40 minutes would keep all four subjects: even Languages has a total of 100 minutes. That would select categories by their combined time rather than select sessions by their individual duration.
The diagram shows how selecting observations first determines which records contribute to each category’s total.
Select observations before adding their values within each category.
These prepared tables will supply the values for our charts. First, the next chapter uses medians and percentiles to describe the center and spread of the individual durations. We will then handle missing measurements before drawing the results.
Check Your Understanding
- What does one row represent before grouping, and what does one row represent after a grouped sum?
- Two subjects have the same session count. Does that imply the same total time? Which values would you compare?
- A report ranks rooms by total minutes but describes the result as “average booking length”. Why can that ranking be misleading, and what would you calculate and sort instead?
- To compare time spent in sessions lasting at least 40 minutes, a program calculates subject totals and then removes totals below 40. Why does this answer a different question, and where should the selection happen?