Skip to content
Analyzing and Visualizing Data

Putting the Analysis Together


Learning Objectives

  • You can connect selection, grouped calculations, and drawing helpers in an analysis.
  • You can explain how the selected observations and grouped calculation determine a result’s meaning.
  • You can adapt the analysis to new records and save a grouped numerical summary.

The previous chapters developed the pandas calculations and then the seaborn charts. We can now connect them into reports and check that the outputs describe the same observations. The new operation in this chapter is saving a numerical table as CSV.

Worked Example: Reusing a Drawing Function

In Selecting Before Grouping, you selected individual records before calculating grouped results. In Drawing with a Function, you drew a prepared table on an Axes supplied by the caller. A report function can connect these steps: prepare the summary, pass it and the supplied Axes to a drawing helper, then return the summary for inspection or reuse.

The following worked example reuses the draw_subject_totals function from Drawing with a Function. Follow the table through the selection, grouping, and drawing steps:

def draw_long_session_totals(sessions, minimum, ax):
selected = sessions[sessions["minutes"] >= minimum]
totals = selected.groupby("subject", as_index=False)["minutes"].sum()
totals = totals.sort_values("minutes", ascending=False)
draw_subject_totals(totals, ax)
return totals

With minimum=40, the prepared table contains Mathematics with 315 minutes, Programming with 175, and Writing with 110. The existing drawing helper handles the labels. The same table is drawn and returned; the caller still owns the Figure. Reusing a helper keeps its drawing code in one place.

Saving the Numerical Summary

A chart displays the comparison, but another program may need the calculated values themselves. This example uses the original sessions.csv from Reading the Study Session CSV. Replace analysis.py with this example, which writes the grouped values as CSV:

import pandas as pd
sessions = pd.read_csv("sessions.csv")
totals = sessions.groupby("subject", as_index=False)["minutes"].sum()
totals = totals.sort_values("minutes", ascending=False)
totals.to_csv("subject-totals.csv", index=False)

The resulting file contains:

subject,minutes
Programming,350
Mathematics,315
Writing,150
Languages,100

index=False leaves out the DataFrame’s index labels, which identify rows within the table rather than another recorded measurement. The column names form the header, even when the table has no rows. This call writes the table in its current order and replaces an existing file at the given path, so use an output filename separate from sessions.csv.

In the next exercise, the starter already prepares and sorts the booking totals. Add the CSV output operation to save that table at the supplied path:

Saving Booking Totals

0 / 30 points

Complete write_category_totals(bookings, path). The starter already calculates total minutes for each category and sorts the totals from largest to smallest. Add the CSV output operation to save the prepared totals table at path.

Use exactly the columns category and minutes, in that order, with a header and no DataFrame index. For records quiet: 20, group: 40, and quiet: 30, save:

category,minutes
quiet,50
group,40

Tied categories may appear in either order. An empty input writes only the header. Replace any existing file; the parent folder exists. Categories and numeric durations have no missing values. Leave bookings unchanged. The function need not return a value.

A Complete Analysis Script

Replace analysis.py in data-analysis with the script below. It combines the earlier calculations and charts using the original 24-row sessions.csv from Reading the Study Session CSV. The bar chart receives grouped totals; the histogram receives individual measured sessions, as in Drawing a Histogram.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sessions = pd.read_csv("sessions.csv")
usable = sessions.dropna(subset=["minutes"])
print("Usable sessions:", len(usable))
print("Omitted sessions:", len(sessions) - len(usable))
print("Recorded minutes:", usable["minutes"].sum())
print("Mean minutes:", usable["minutes"].mean())
writing = usable[usable["subject"] == "Writing"]
print("Writing mean minutes:", writing["minutes"].mean())
print("Writing median minutes:", writing["minutes"].median())
totals = usable.groupby("subject", as_index=False)["minutes"].sum()
totals = totals.sort_values("minutes", ascending=False)
print(totals)
totals.to_csv("subject-totals.csv", index=False)
fig, ax = plt.subplots()
sns.barplot(data=totals, x="subject", y="minutes", errorbar=None, ax=ax)
ax.set_title("Recorded study time by subject")
ax.set_xlabel("Subject")
ax.set_ylabel("Total time in minutes")
fig.savefig("subject-totals.png", bbox_inches="tight")
plt.close(fig)
fig, ax = plt.subplots()
sns.histplot(data=usable, x="minutes", bins=5, ax=ax)
ax.set_title("Study session lengths")
ax.set_xlabel("Minutes per session")
ax.set_ylabel("Number of sessions")
fig.savefig("session-lengths.png", bbox_inches="tight")
plt.close(fig)

Run the script using the environment’s Python interpreter. It prints the counts, calculations, and grouped table, and saves one summary CSV and two PNG files. If a result surprises you, print the table just before the operation that uses it to check what each row represents.

Checking the Results

The original sample has no missing durations, so all 24 sessions contribute. The first printed results are:

Usable sessions: 24
Omitted sessions: 0
Recorded minutes: 915
Mean minutes: 38.125
Writing mean minutes: 50.0
Writing median minutes: 25.0

The four totals in subject-totals.csv should match the CSV example above and add to 915. The histogram’s counts should add to 24.

Reporting another unit

As an optional variation, reuse the calculated hours column from Calculating a Column to prepare a summary in hours. Give the output column its unit and save it to a separate file. The subject totals should add to 915 / 60, or 15.25 hours, with the same subject ordering as the minute totals.

The Writing mean of 50 minutes exceeds two of its three recorded durations, 15 and 25 minutes. Its median is 25 minutes. Together with the histogram’s isolated 110-minute observation, this comparison gives a reason to inspect the individual records before describing a typical session. The histogram alone does not identify that observation’s subject.

These checks compare the outputs with the records they summarize. The duration rule also applies to the separate missing-sessions.csv example from Missing Values and Recorded Zeros. Reading that file instead gives three usable sessions and one omitted session, a recorded total of 60 minutes, and a mean of 20 minutes. There are no Writing observations in that file, so neither Writing summary has a value to report. The unknown duration remains unknown.

Commute Duration Analysis

The same workflow can compare average journey lengths to campus. The new records have a mode column for travel mode and a minutes column for each journey’s duration. Calculate a mean for each mode, using the distinction explained in Comparing Totals and Averages.

Build the commute report in three exercises. Each later exercise unlocks after the preceding one is complete and supplies its completed functions, so you can focus on the next step.

First, read the supplied CSV and keep journeys with measured durations, including recorded zeros. The starter provides the two count labels. Replace its None placeholders with the usable count, the omitted count, and the returned table. Calculate the omitted count from the difference between the original and retained row counts.

Commute Analysis: Read

0 / 15 points

Complete load_commutes(path). Read the CSV and return journeys whose minutes value is present. Keep recorded zeros, all columns, row labels, and row order. A missing value in another column does not remove a journey.

The starter supplies the two print labels. Replace the None count placeholders with the usable and omitted row counts, and replace the final return None with the usable table. The completed output has the form Usable journeys: N followed by Omitted journeys: N.

Use the supplied path and leave the file unchanged. A header-only file or a file with no measured durations returns an empty table with the original columns.

The next starter includes the completed reader, which prints these counts when called. Calculate one mean duration per travel mode and put the longest mean first, using the grouped calculation from Group Comparisons. With no usable journeys, there are no groups: the result has its two column names and no rows, rather than a mean of zero for a travel mode.

Commute Analysis: Summarize

0 / 20 points

Complete mean_durations(trips). Return one mean duration per travel mode, with columns mode and minutes, ordered from longest mean to shortest. Tied means may appear in either order.

The completed reader prints the usable and omitted counts and supplies journeys with measured durations. Travel-mode names are present. Leave trips unchanged. An empty input returns an empty table with the two result columns.

The final starter supplies the reader, summary function, and drawing helper. Connect them in that order. Use the same mean table for drawing, CSV output, and the return value. The caller saves the Figure; your report saves the numerical table. The reader’s printed usable and omitted counts remain part of the report.

Commute Analysis: Report

0 / 15 points

Complete analyze_commutes(input_path, output_path, ax) using the supplied reader, summary function, and drawing helper.

Read the usable journeys with load_commutes, calculate their means with mean_durations, and pass the summary and ax to draw_commute_means. The output includes the reader’s two journey-count lines. Save that same ordered summary to output_path as CSV with its mode,minutes header and no index column. Return the summary.

Travel-mode names are present, and the input has at least one measured journey. The output path differs from the input, and its parent folder exists. Replace any earlier output; leave the input file unchanged.

Check Your Understanding

  1. What would you check if the sum of the subject totals differed from the total of the usable session durations?
  2. When changing a report from totals to means, which calculation and labels need to change, and which steps can stay the same?
  3. The commute reader reports one omitted journey. Why should that count remain visible when the grouped means and chart are presented? Which journeys do those means describe?