Sub topic 8
Counting categories
Counting categories is the first step in understanding columns that hold labels instead of measurements. You count how many rows fall into each label, check how many rows have no label, and spot labels that don't belong. This chapter assumes you have loaded train.csv into df, as in the earlier chapters, and that you know Series and DataFrame basics. It uses pandas 2.x.
Which columns are categorical?
A categorical column holds a small set of labels instead of a quantity you can average. In the Titanic table, some of these columns are obvious and some are not.
| Column | Stored as | Treat as | Distinct values |
|---|---|---|---|
| `Sex` | text | category | 2 |
| `Embarked` | text | category | 3 (plus 2 missing) |
| `Pclass` | integer | category | 3 |
| `Survived` | integer | category (0 or 1) | 2 |
| `Name` | text | identifier | 891 |
| `Ticket` | text | near-identifier | 681 |
| `Cabin` | text | high-cardinality category | 147 (687 missing) |
The dtype does not decide this. Pclass is stored as an integer, but "class 3" is not three times "class 1", so you count it rather than average it. Name is text but identifies one passenger each, so counting it tells you nothing.
A quick scan with describe
For text columns, describe with include="object" gives a compact summary:
print(df.describe(include="object"))For each text column it reports count (non-missing rows), unique (distinct values), top (the most frequent value), and freq (how often top occurs). This tells you quickly that Name has 891 unique values out of 891 rows, so it is an identifier. It also shows that Cabin has only 204 non-missing entries. Note that describe does not show the other labels. For that you need value_counts.
Counting values with value_counts
Series.value_counts() returns one row per distinct value, sorted from most to least frequent:
print(df["Embarked"].value_counts(dropna=False))Embarked
S 644
C 168
Q 77
NaN 2
Name: count, dtype: int64The dropna=False argument matters. By default, value_counts silently leaves out missing values, so the counts add up to fewer than 891 and you may not notice. Setting dropna=False adds a NaN row, which makes the two passengers with no recorded port visible.
Counts and shares together
Counts say how many. Proportions say how much of the whole. Use normalize=True for proportions, and put both side by side:
counts = df["Embarked"].value_counts(dropna=False)
shares = (df["Embarked"].value_counts(normalize=True, dropna=False) * 100).round(1)
embarked_summary = pd.DataFrame({"count": counts, "percent": shares})
print(embarked_summary)With dropna=False, the proportions are shares of all 891 rows, so S is 72.3%. If you left dropna at its default, normalize=True would divide by 889 instead, and S would be 72.4%. Neither is wrong, but you should know which denominator you are using.
Looping over several columns
When you want a quick pass over every categorical column, a loop is enough:
for col in ["Sex", "Pclass", "Embarked", "Survived"]:
print(df[col].value_counts(dropna=False).sort_index())
print()sort_index() orders the rows by label instead of by frequency. For ordered labels like Pclass (1, 2, 3), this is usually easier to read. It also puts NaN last.
High-cardinality columns
Cardinality is the number of distinct values in a column. nunique() measures it for several columns at once:
print(df[["Name", "Sex", "Ticket", "Cabin", "Embarked"]].nunique())By default, nunique ignores missing values. A value_counts on Name would print 891 rows of count 1, which is noise. A good rule: if nunique() is close to the row count, the column is an identifier. If it is far smaller than the row count but still large, as with Ticket (681), shared values are meaningful. Several passengers shared a ticket, which usually means they traveled together. That is worth a closer look later.
Extracting a category from messy text
Cabin values like C85 or E46 combine a deck letter with a number. Counting the raw values gives 147 mostly-singleton rows. The first letter is the useful category:
deck_counts = df["Cabin"].str[0].value_counts(dropna=False)
print(deck_counts)The .str[0] accessor takes the first character of each string and leaves missing values as NaN. The result shows that 687 passengers have no cabin recorded, far more than any deck. The deck T appears only once, which is a reminder that tiny categories can't support conclusions.
Counting two categories at once
pd.crosstab counts how many rows fall into each combination of two columns:
print(pd.crosstab(df["Pclass"], df["Sex"]))
print(pd.crosstab(df["Pclass"], df["Sex"], normalize="index").round(2))The first call produces this table of counts:
| Pclass | female | male |
|---|---|---|
| 1 | 94 | 122 |
| 2 | 76 | 108 |
| 3 | 144 | 347 |
With normalize="index", each row sums to 1, so you read it as "within each class, what share was female?" Use normalize="columns" to make each column sum to 1 instead. Choosing the wrong direction is a common error, so say aloud which group you are conditioning on before you read the table. Third class is about 71% male, which will matter when you compare survival across groups later.
By default crosstab does not show missing values. Pass dropna=False if you want rows or columns for them.
Making categories explicit
If you want pandas to treat a column as a fixed set of labels, convert it with the category dtype:
df["Embarked"] = df["Embarked"].astype("category")
print(df["Embarked"].cat.categories)
print(df["Embarked"].value_counts(dropna=False))Converting an existing column changes df, so do this deliberately. The benefits are lower memory use and a fixed list of valid labels. One side effect to know: value_counts on a categorical column also lists categories with zero rows. That is useful for spotting a label that should exist but doesn't, and it can surprise you in groupby output, which is why the observed=True argument appears elsewhere in this tutorial.
Common errors
- Forgetting
dropna=False. Counts silently exclude missing values, and the total no longer matches the row count. Comparecounts.sum()withlen(df)as a check. - Counting an identifier.
value_countsonNameorTicketproduces long, meaningless output. Checknunique()first. - Inconsistent labels.
"male","Male", and" male"would count as three categories. Test withdf["Sex"].str.strip().str.lower().nunique()and compare it todf["Sex"].nunique(). If they differ, you have a cleaning problem. In this file they are equal. - Reading a share with the wrong denominator. "72% of passengers boarded at S" and "72% of passengers with a recorded port boarded at S" are slightly different claims.
- Trusting a small category. A share of 100% from one passenger is not a pattern.
The counting routine
What to record
After counting, write down short facts with their denominators. For this table: 891 passengers, 577 male and 314 female. The port is missing for 2 passengers. About 77% of Cabin values are missing, so deck cannot be used without caveats. Name is an identifier. Ticket is shared by some passengers. These notes feed directly into the missing-value, grouping, and interpretation chapters.
Exercise
Using df, write code that shows the share of passengers in each Pclass as percentages rounded to one decimal, ordered by class number. Then explain why df["Pclass"].value_counts(normalize=True) and the same call with dropna=False give identical results for this column.
Show answer
Use (df["Pclass"].value_counts(normalize=True) * 100).round(1).sort_index(). This gives class 1 as 24.2, class 2 as 20.7, and class 3 as 55.1. Both calls match because Pclass has no missing values, so the denominator is 891 either way. You can confirm this with df["Pclass"].isna().sum(), which returns 0.
Exercise
You run pd.crosstab(df["Pclass"], df["Sex"], normalize="index") and see 0.29 in the row for class 3, column female. Write one sentence saying what this means, then name the argument you would change to get "of all women, what share traveled in each class?"
Show answer
Of the third-class passengers, 29% were female (144 of 491). Change normalize="index" to normalize="columns", so each column sums to 1 and you read the share of women in each class.