Sub topic 2
Counting problems by category
This chapter covers the first step of every Pareto analysis: turning a pile of problem records into a frequency table. The chart and the cumulative line come from that table, so any error in it carries through to every later step. It assumes you can read a bar chart, compute a percentage, and write basic pandas code (DataFrame, Series, value_counts).
Categorical data and frequency
A categorical variable puts each observation into a named group, such as defect type, complaint reason, machine, or shift. A frequency count is the number of observations in each group. A frequency table lists every category with its count.
Pareto analysis needs this kind of data. A measurement like "length of the part in millimetres" is numeric and has no natural groups. A record like "part rejected because of a scratch" has a category you can count.
The three common ways to get categories are:
- Reading a label someone already recorded, such as a defect code in an inspection system.
- Classifying free text, such as sorting customer complaints into reasons.
- Binning a numeric or time variable into groups, such as late deliveries by carrier.
In all three cases, the quality of the counts depends on how consistently each record was assigned to a category.
From raw records to a frequency table
Real data rarely arrives as counts. It arrives as one row per event. The pipeline looks like this:
Here is a small inspection log with the usual flaws: inconsistent capitalization and a trailing space.
import pandas as pd
log = pd.DataFrame({
"unit_id": [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112],
"defect": [
"Scratch", "scratch ", "Misalignment", "Wrong label",
"Scratch", "Cracks", "misalignment", "Scratch",
"Wrong Label", "Discoloration", "Scratch", "Cracks",
],
})
print("Before cleaning:")
print(log["defect"].value_counts())
# Normalize: strip whitespace, lowercase, then capitalize the first letter
log["defect"] = log["defect"].str.strip().str.lower().str.capitalize()
print("\nAfter cleaning:")
print(log["defect"].value_counts())Before cleaning, "Scratch" and "scratch " are counted as different categories, and so are "Wrong label" and "Wrong Label". The result is a longer list with smaller counts. After cleaning there are five categories:
| Category | Count |
|---|---|
| Scratch | 5 |
| Misalignment | 2 |
| Wrong label | 2 |
| Cracks | 2 |
| Discoloration | 1 |
The order of tied categories (Misalignment, Wrong label, and Cracks all have 2) is not meaningful. If you need a stable order, sort by count and then by name.
value_counts() already returns counts sorted from largest to smallest. That is the order a Pareto chart needs, but a later chapter treats the sorting rules, including where the "Other" bucket goes.
What counts as one observation
Before you count, decide what a single count represents. Three choices come up often.
Units, defects, or incidents
A single product can have several defects. If unit 204 has a scratch and a crack, you can count:
- Defects: two records, one per defect.
- Defective units: one unit.
These give different totals and different percentages. The right choice depends on the question. If you want to reduce scrapped products, count units. If you want to reduce rework actions or fix each defect type at its source, count defects.
import pandas as pd
records = pd.DataFrame({
"unit_id": [201, 202, 203, 204],
"defects": [
["Scratch"],
["Scratch", "Crack"],
[],
["Misalignment", "Scratch", "Crack"],
],
})
# One row per (unit, defect) pair; units with no defects become NaN and are dropped
exploded = records.explode("defects").dropna(subset=["defects"])
defect_counts = exploded["defects"].value_counts()
units_per_defect = exploded.groupby("defects")["unit_id"].nunique()
print("Defect occurrences:", len(exploded))
print("Units with at least one defect:", exploded["unit_id"].nunique())
print(defect_counts)
print(units_per_defect)Here there are 6 defect occurrences across 3 defective units out of 4 inspected. Scratch accounts for 3 of 6 defects (50%) but appears on 3 of 4 inspected units (75%). Both numbers are correct. They answer different questions, so state which denominator you use.
Mutually exclusive records
If you classify each record into exactly one category (for example, the primary cause of a complaint), the counts add up to the number of records. If one record can fall in several categories, the counts add up to more than the number of records. Percentages of the total then do not match percentages of the records. A Pareto chart's cumulative line assumes the counts add up to a meaningful whole, so be explicit about which case you have.
The time window
A count is only meaningful for a stated period. "42 scratches" means little without "in the inspection period of week 12" or "in Q3". Use a window long enough to include normal variation, such as several shifts or several weeks, but not so long that it mixes before and after a process change.
Designing the categories
The categories you define shape every result. Good category sets share these properties:
- Mutually exclusive. A record fits in one category, not two. If "Wrong label" and "Printing error" overlap, people will file the same problem both ways.
- Collectively exhaustive. Every record fits somewhere. An "Other" bucket guarantees this.
- Actionable. A category should point toward something a team can investigate. "Operator error" is rarely actionable because it hides the underlying causes. "Setup sheet missing step 4" is.
- Consistent in granularity. Do not mix "Scratches" (a broad type) with "Scratch on left panel, shift 2" (a very narrow one) in the same list.
The number of categories matters too. Too few (two or three) hides the structure. Too many (30 or more) leaves each with a small count and makes the chart hard to read. A practical range is roughly 5 to 12 named categories plus "Other".
Handling the "Other" bucket
"Other" collects rare or unclassifiable records. It is useful, but it can grow too large. A common rule of thumb is that if "Other" is larger than your biggest named category, the category scheme is failing and needs revision. Look inside the bucket and see whether a recurring item deserves its own category.
import pandas as pd
counts = pd.Series({
"Scratches": 42, "Misalignment": 27, "Wrong label": 11,
"Cracks": 8, "Discoloration": 5, "Burrs": 2, "Dents": 3, "Smudges": 2,
})
min_count = 6
named = counts[counts >= min_count]
other_total = counts[counts < min_count].sum()
table = pd.concat([named, pd.Series({"Other": other_total})])
print(table)
print("Total:", table.sum())This folds Discoloration (5), Burrs (2), Dents (3), and Smudges (2) into an "Other" bucket of 12. The total stays at 100, which confirms that no records were lost. After any regrouping, check that the sum of the counts equals the number of records you started with.
Common counting mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Spelling or case variants counted separately | Categories look smaller and the ranking shifts | Normalize labels before counting |
| Counting defects in one place and units in another | Percentages do not reconcile | Choose one counting unit and state it |
| A record assigned to several categories | Counts add to more than the number of records | Use a primary-cause rule or document the overlap |
| Missing values dropped silently | The total is too small | Count missing values explicitly as "Unclassified" |
| Very short observation window | One unusual day dominates | Collect over a representative period |
| Categories defined after seeing the data to fit a story | Biased conclusions | Fix the category list before counting where possible |
Missing values deserve special care. value_counts() drops NaN by default. Use value_counts(dropna=False) to see how many records have no category. If many do, report that number. Unclassified records are a data-collection problem, and they change what the ranking can tell you.
Checking the frequency table
Before moving on, run three quick checks on the finished table:
- The counts sum to the number of records (or defects) you expect.
- No category appears twice under a slightly different name.
- "Other" and "Unclassified" are small relative to the largest named categories.
If these pass, the table is ready for the next step. The following chapters use these counts to compute cumulative percentages and to draw the chart. The ranking at the top of your table is the first draft of your vital few, but whether it is a reliable one depends on the choices above: the counting unit, the category definitions, and the time window.
Exercise
An inspection log lists 200 units. 60 have at least one defect, and those 60 units carry 90 defect records in total. Misalignment appears in 36 defect records, on 30 distinct units. What percentage is Misalignment (a) of all defect records and (b) of the defective units? Which would you use to decide how many units to rework, and why?
Show answer
(a) 36 / 90 = 40% of defect records. (b) 30 / 60 = 50% of defective units. To decide how many units need rework, use the unit-based figure (b), because rework is done per unit, and a unit with several misalignment records is still reworked once. The record-based figure (a) suits questions about how often the defect type occurs.
Exercise
A table of customer complaint reasons shows "Late delivery" 31, "late delivery" 9, "Damaged" 22, "Wrong item" 18, and "Other" 20. What is wrong with the table, and how does fixing it change which category is largest?
Show answer
"Late delivery" and "late delivery" are the same category split by capitalization. Merging them gives 40 for "Late delivery", so it stays the largest category (40 versus 22 for the next one, Damaged), but its share of the 100 complaints rises from 31% to 40%. Before the fix, its apparent size understated the problem. Normalize labels (for example with str.strip().str.lower()) before counting.