Sub topic 8
Load, inspect, and plot a dataset
This chapter assumes you finished the earlier setup chapters. You have a virtual environment with JupyterLab, pandas, and matplotlib installed. You have registered it as a kernel and selected it in a notebook. You should also be able to run cells and know what a CSV file is.
Here you load a CSV file into a pandas DataFrame, check that it loaded correctly, and draw your first plots. The inspection step matters most. Most analysis bugs come from data that loaded in a slightly wrong shape, and a plot often hides them.
The workflow
Treat loading as three steps: read the file, inspect what you got, then plot. Inspect before you plot, because a plot of wrongly typed data can look plausible and still be wrong.
Create a sample file
The examples use data/sales.csv with a revenue column. If you don't have a file, run this cell to generate one. The seed makes the numbers identical on every run, and five revenue values are blanked on purpose so you have missing data to find.
from pathlib import Path
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 200
Path("data").mkdir(exist_ok=True)
sample = pd.DataFrame({
"order_date": pd.date_range("2025-01-01", periods=n, freq="D"),
"region": rng.choice(["North", "South", "East", "West"], size=n),
"units": rng.integers(1, 20, size=n),
"revenue": rng.gamma(shape=2.0, scale=150.0, size=n).round(2),
})
sample.loc[rng.choice(n, size=5, replace=False), "revenue"] = np.nan
sample.to_csv("data/sales.csv", index=False)The path data/sales.csv is relative to the notebook's working directory, which is the folder containing the notebook file. If you get FileNotFoundError, run %pwd in a cell to see where the kernel is looking.
Load the file
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data/sales.csv")pd.read_csv returns a DataFrame, a table with labelled columns and a row index. Put the imports in the first cell of the notebook. Anyone reading it can then see the dependencies at once.
Inspect the data
Run these three calls first on any new dataset.
df.head()
df.info()
df.describe()In a notebook cell, only the value of the last expression is displayed automatically. Here df.head() produces a result that is thrown away, because df.describe() comes last. df.info() still shows its output because it prints directly instead of returning a value. To see several results from one cell, wrap them in display(), or put each in its own cell.
display(df.head())
df.info()
display(df.describe())Each call answers a different question.
| Call | What it tells you | What to look for |
|---|---|---|
| `df.head()` | The first five rows | Columns shifted, header rows read as data, odd separators |
| `df.info()` | Column names, dtypes, non-null counts, memory use | Numbers stored as `object`, dates stored as `object`, columns with fewer non-null values than rows |
| `df.describe()` | Count, mean, standard deviation, min, quartiles, max for numeric columns | Negative values where none should exist, a maximum far above the 75th percentile |
Read `info()` carefully
For the sample file, info() shows order_date with dtype object, which means plain strings. revenue shows 195 non-null values out of 200 rows, which is the missing data. region is also object, which is correct for text.
A numeric column showing object usually means some cell contains text such as "N/A", "$1,200", or a stray space. pandas falls back to strings for the whole column when it finds one value it cannot parse as a number. Fix this at read time with options like na_values=["N/A", "-"] or thousands=",".
Check missing values directly
df.isna().sum()This counts missing values per column. Plotting and statistics functions skip missing values by default, so a column with many gaps can yield results based on far fewer rows than you expect. Always compare the counts against the row count from df.shape.
Fix types while reading
Tell pandas which columns are dates when you load the file. It is cleaner than converting afterwards.
df = pd.read_csv(
"data/sales.csv",
parse_dates=["order_date"],
dtype={"region": "category"},
)
df.info()order_date is now datetime64[ns], which unlocks date-based operations such as resampling. The category dtype stores repeated strings compactly and makes the set of valid values explicit.
Two other read_csv options come up often:
usecols=["order_date", "revenue"]loads only the listed columns, which saves memory on wide files.nrows=1000loads only the first 1000 rows, which is useful for a quick look at a very large file.
Plot with matplotlib through pandas
pandas DataFrames and Series have a .plot() method that calls matplotlib for you. A histogram shows how the values of one column are distributed.
df["revenue"].plot(kind="hist", bins=20)
plt.show()bins=20 splits the value range into 20 equal-width buckets and counts rows in each. Try 10 and 50 as well. Too few bins hide structure, and too many make the shape noisy. In the sample data you should see a right-skewed shape with a long tail of large orders. That agrees with what describe() showed: a mean above the median (the 50% row) and a maximum far above the 75th percentile.
Two other plots cover most first-pass questions. This cell compares totals across categories with a bar chart, then shows a trend over time with a line chart.
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
df.groupby("region", observed=True)["revenue"].sum().plot(
kind="bar", ax=axes[0], title="Revenue by region"
)
axes[0].set_xlabel("Region")
axes[0].set_ylabel("Total revenue")
monthly = df.set_index("order_date")["revenue"].resample("MS").sum()
monthly.plot(ax=axes[1], marker="o", title="Revenue by month")
axes[1].set_xlabel("Month")
axes[1].set_ylabel("Total revenue")
fig.tight_layout()
plt.show()The pieces here:
plt.subplots(1, 2, figsize=(11, 4))creates a figure with two side-by-side axes. Passingax=axes[0]tells pandas which one to draw on.groupby("region")splits the rows by region, and["revenue"].sum()totals each group.observed=Truelimits the result to categories that appear in the data, which avoids a pandas warning for category columns.resample("MS")groups a date-indexed series into calendar months labelled by month start. It needs a datetime index, which is whyset_index("order_date")comes first. That index only works becauseparse_datesconverted the column earlier.- Axis labels are set on each
Axesobject. A plot with no labels or units is hard to read later, including by you.
Common mistakes
- Plotting before inspecting. A histogram of a column stored as strings fails or plots the wrong thing. Check
info()first. - Reading the wrong working directory. Relative paths resolve against the notebook's folder, not your terminal's. Use
%pwdto check. - Ignoring missing values. A mean over 195 rows is not a mean over 200. Compare
isna().sum()withshape. - Overwriting
dfwhile experimenting. If you re-run a cell that reassignsdfafter dropping rows, the result depends on how many times you ran it. Reload from the file or build a new variable such asclean = df.dropna(subset=["revenue"]). This ties into hidden state, which a later chapter covers. - Recording the plot but not the data checks. Leave your
info()andisna()cells in the notebook. They document what you verified.
Exercise
You load a file with pd.readcsv and info() reports that the "price" column has dtype object, although every value looks like a number when you open the file in a text editor. Name two likely causes and one readcsv option for each.
Show answer
Likely causes are a non-numeric placeholder such as "N/A" or "-" in some rows, and numbers formatted with thousands separators or currency symbols such as "1,200". For placeholders, pass navalues=["N/A", "-"] so pandas treats them as missing and parses the rest as numbers. For thousands separators, pass thousands="," (a currency symbol such as "$" must be stripped separately, for example with str.replace followed by astype(float) after loading). You can also inspect the offending values with pd.tonumeric(df["price"], errors="coerce") and look at the rows that become NaN.
Exercise
Why does df.resample("MS") raise an error when orderdate was loaded without parsedates, and what are two ways to fix it?
Show answer
resample needs a datetime index, and without parsedates the column holds strings. Fix it by passing parsedates=["orderdate"] to readcsv, or by converting afterwards with df["orderdate"] = pd.todatetime(df["orderdate"]). Then call setindex("order_date") before resample.