Sub topic 9
Looking at one variable at a time
This chapter covers univariate analysis: describing a single column before you relate it to others. It assumes you can read a pandas DataFrame, know the mean, median and distribution from introductory statistics, and have already built a cleaned df as in the earlier chapters. Examples use the orders data, with columns such as amount, region and order_date.
Why start with one variable
Univariate analysis answers a narrow question: what does this column look like on its own? You need the answer before you compare columns. If amount has a long tail or a block of zeros, any average you report later inherits that problem.
This step also catches problems the quality audit missed. A column can have no missing values and the right dtype, and still be unusable. For example, every value might be identical, or one category might make up 99% of rows.
Treat each column as one of three kinds, because the kind decides which summary and plot to use.
| Kind | Example column | Summary | Plot |
|---|---|---|---|
| Numeric | `amount` | count, mean, median, std, quantiles | histogram, box plot |
| Categorical | `region` | counts and proportions per level | bar chart |
| Datetime | `order_date` | range, counts per period | line plot of counts over time |
A repeatable order of work
Take the same steps for every column. A fixed routine keeps the notebook readable and stops you skipping a column because it looked boring.
Numeric columns
Start with numbers, then draw the plot. The numbers tell you what to look for in the picture.
amount = df["amount"]
summary = amount.describe(percentiles=[0.01, 0.25, 0.5, 0.75, 0.99])
summary["skew"] = amount.skew()
summary["share_zero"] = (amount == 0).mean()
print(summary.round(2))Read these values together:
- Mean versus median. If the mean is well above the median, a few large values pull it up. That pattern is called right skew.
- The 1st and 99th percentiles against the min and max. If the max is far beyond the 99th percentile, a handful of extreme values exist. Decide later whether they are errors or real.
- Share of zeros. A spike at zero often means a different process, such as cancelled or free orders. It may deserve separate treatment.
Histograms and bin choice
A histogram groups values into bins and counts them. The number of bins changes what you see. Too few bins hide structure. Too many produce noise.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(14, 4), sharey=False)
for ax, bins in zip(axes, [10, 30, 100]):
df["amount"].plot.hist(bins=bins, ax=ax)
ax.set_title(f"Order amount, {bins} bins")
ax.set_xlabel("Amount")
ax.set_ylabel("Number of orders")
plt.tight_layout()
plt.show()Try at least two bin counts before you believe a shape. A second peak that appears at 100 bins but not at 10 may be real, or it may be noise. Check it against the data, for example by counting values in that range.
Skewed data and the log scale
When values span several orders of magnitude, most of a histogram sits in one bar. A log transform spreads them out. Use np.log1p, which computes log(1 + x) and so handles zeros.
import numpy as np
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
df["amount"].plot.hist(bins=40, ax=axes[0])
axes[0].set_title("Amount, original scale")
axes[0].set_xlabel("Amount")
axes[0].set_ylabel("Number of orders")
np.log1p(df["amount"]).plot.hist(bins=40, ax=axes[1])
axes[1].set_title("Amount, log1p scale")
axes[1].set_xlabel("log(1 + amount)")
axes[1].set_ylabel("Number of orders")
plt.tight_layout()
plt.show()Keep the transformed values in the plot call, not in df. Adding a column is a cleaning decision, and it belongs in the cleaning function so it is recorded and re-runnable.
Outliers: flag, then decide
The interquartile range (IQR) rule is a common first screen. A value is flagged if it lies more than 1.5 IQRs beyond the first or third quartile. Box plots use the same rule for their whiskers.
q1, q3 = df["amount"].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
flagged = df[(df["amount"] < low) | (df["amount"] > high)]
print(f"bounds: {low:.2f} to {high:.2f}")
print(f"flagged: {len(flagged)} of {len(df)} rows ({len(flagged) / len(df):.1%})")
flagged.sort_values("amount", ascending=False).head()The rule only flags. It does not say a value is wrong. On a skewed column it flags many legitimate large values. Look at the flagged rows, and record what you find. Do not drop them in this section.
Categorical columns
For a categorical column, count the levels and look at proportions. Include missing values so they are not hidden.
region_counts = df["region"].value_counts(dropna=False)
region_share = df["region"].value_counts(normalize=True, dropna=False).round(3)
print(pd.DataFrame({"count": region_counts, "share": region_share}))
print("distinct levels:", df["region"].nunique())Things to look for:
- Near-duplicate levels. Values like
northandnorthorNorthshould have been merged during cleaning. If both appear, the cleaning function is incomplete. - Rare levels. A level with three rows cannot support any comparison later. Note it, and decide whether to group rare levels into "other".
- Dominant levels. If one level holds nearly all rows, the column carries little information.
- High cardinality. If the number of distinct values is close to the number of rows, the column is probably an identifier, not a category.
Plot counts as a bar chart, sorted from largest to smallest, so the order carries meaning.
ax = df["region"].value_counts().plot.bar(figsize=(6, 4))
ax.set_title("Orders per region")
ax.set_xlabel("Region")
ax.set_ylabel("Number of orders")
plt.tight_layout()
plt.show()Datetime columns
A date column is useful in two ways. Its range tells you what period the data covers, and counts per period reveal gaps and trends.
dates = df["order_date"]
print("from", dates.min(), "to", dates.max())
orders_per_month = df.set_index("order_date").resample("MS").size()
ax = orders_per_month.plot(marker="o", figsize=(8, 4))
ax.set_title("Orders per month")
ax.set_xlabel("Month")
ax.set_ylabel("Number of orders")
plt.tight_layout()
plt.show()Watch for months with zero or unusually few orders. They may be real, or they may be an extract that stopped early. The last month is often partial, which makes it look like a drop. Compare it with the maximum date before reading it as a trend.
Edge cases
- Small samples. With a few hundred rows, a histogram is jagged and quantiles are unstable. Prefer fewer bins and avoid strong claims.
- Discrete numbers. Integer counts such as items per order produce gaps between bins. Use a bar chart of
value_counts()instead of a histogram. - Constant columns. If
nunique()is 1, the column cannot explain anything. Note it and consider dropping it from later analysis. - Plots hide missing values. Histograms silently skip NaN. Report the missing count next to the plot.
- Sentinel values. Codes such as
-1or9999standing for "unknown" appear as strange spikes. A spike at one exact value is a hint to check.
Record what you see
After each column, write a short markdown cell in the format from the findings chapter. State the observation, the evidence, a hypothesis and a next step. For example:
### Finding: region is dominated by one level
- **Evidence:** `value_counts(normalize=True)` shows `north` at 71% of rows.
- **Hypothesis:** the extract over-represents one sales channel.
- **Next step:** compare the amount distribution of `north` against the others.Keep hypotheses worded as hypotheses. A single histogram cannot establish a cause.
Exercise
A histogram of amount shows one tall bar at the far left and almost nothing else. The max is 250,000 and the 99th percentile is 900. Name two checks you would run next, and say whether you would drop the large values at this point.
Show answer
First, plot the data on a log scale with np.log1p, or restrict the plot to values at or below the 99th percentile, so the bulk of the distribution is visible. Second, inspect the rows above the 99th percentile (sort descending and read them) to see whether they are data entry errors, test orders, or genuine large purchases. Do not drop them in the univariate section. Record what you find in a findings cell, and make any removal an explicit, documented rule in the cleaning function.
Exercise
df["region"].nunique() returns 4,812 in a table of 5,000 rows. What does this suggest, and how does it change how you treat the column?
Show answer
The column is close to unique per row, so it is probably an identifier or free text, not a category. A bar chart of its levels would be meaningless. Treat it as an ID or text field, check for duplicates in it, and exclude it from categorical comparisons unless you group or parse it.