Chapter DData: tables and simple plotsPage 1 of 8

Data: tables and simple plots

Define the lab goal and success criteria

Tables organize observations into rows and named columns, while summary statistics and plots expose scale, missing values, outliers, and relationships before modeling.

~13 minLab goal

1Try it yourself

Code Lab

Data: tables & simple stats

Run the average, then print the top student name.

Before you start

Why this matters

Before running anything, predict one observable result from the case: a four-row study dataset must be inspected for typical hours, an extreme value, and the relationship between hours and passing. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.

2Learn the idea

Read

Explain the chapter step

Begin by writing the success condition in observable terms. For this case, success is not familiarity with the vocabulary; it is producing a reproducible pandas summary and labeled matplotlib scatter plot saved as study-results.png. Record the starting state so you can distinguish an improvement from a result that was already present.

On this page, the practical job is to state a measurable outcome before changing anything. The running case is a four-row study dataset must be inspected for typical hours, an extreme value, and the relationship between hours and passing.

Read

Run the working example

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("study.csv")
required = {"hours", "passed"}
if missing := required - set(df.columns):
    raise ValueError(f"missing columns: {sorted(missing)}")

print(df["hours"].describe()[["count", "mean", "max"]])
df.plot.scatter(x="hours", y="passed", title="Study hours and outcome")
plt.savefig("study-results.png", dpi=150, bbox_inches="tight")

Expected evidence:

count    4.0
mean     4.5
max      8.0
Name: hours, dtype: float64

The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.

Read

Read it line by line

  1. read_csv creates a DataFrame and infers column types from file values.
  2. set subtraction catches misspelled or absent columns before plotting.
  3. describe computes several summaries and the bracket selection keeps the three used here.
  4. plot.scatter names both axes from columns; savefig creates a reviewable artifact without relying on an interactive window.

These lines form one chain: a CSV table with one learner per row becomes validated column summaries plus a plot whose axes and file path are explicit. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.

Read

Common errors and fixes

  • First failure: KeyError: 'hours' means the header differs, perhaps by capitalization or whitespace. Re-run the smallest command that proves the repair.
  • Second failure: a mean that becomes NaN may indicate an empty or nonnumeric column; inspect df.info() and conversion failures. Preserve the failing input as a test when it represents a realistic mistake.
  • Misleading success: a blank saved image often occurs when savefig runs after closing or clearing the figure. A clean-looking final line cannot cancel contradictory intermediate evidence.

When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.

Read

Evidence for this stage

Check row count, dtypes, missing-value counts, minimum, maximum, and duplicated rows. Compare the plotted points with at least two raw CSV records so swapped axes or the wrong column cannot pass unnoticed.

For the current explain step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.

Deliver the CSV schema, analysis script, printed summary, and PNG together. A reviewer should be able to rerun the command and get the same measured values.

Read

Reflect on the result

Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.

Checking tutor…

Continue learning · glossary & guides
  1. Which line or command establishes the current step's most important fact?
  2. What output would reveal that KeyError: 'hours' means the header differs, perhaps by capitalization or whitespace?
  3. Can a new user reproduce a reproducible pandas summary and labeled matplotlib scatter plot saved as study-results.png from the stated setup?