Sub topic 8
Counting categories
This chapter assumes you have loaded train.csv into a DataFrame named df, as in earlier chapters. You should also know how to select a column with df["Name"], which returns a Series.
Why count categories
A categorical column holds labels instead of measurements. In the Titanic data, Sex, Embarked, and Pclass are categorical. Averages mean little for them. Counts tell you how many rows fall into each group, which is the first thing to check before you compare groups.
Summarizing text columns
describe() skips text columns by default. Pass include="object" to summarize them.
import pandas as pd
df = pd.read_csv("train.csv")
print(df.describe(include="object"))For each text column you get count (non-missing values), unique (distinct values), top (the most common value), and freq (how often it appears). Notice that Name has one unique value per passenger, so it works as an identifier and not as a category. Cabin has many unique values and many missing ones.
Counting with value_counts
value_counts() returns a Series with each distinct value and its count, sorted from most to least common.
print(df["Embarked"].value_counts(dropna=False))By default value_counts() drops missing values. Setting dropna=False keeps them as their own row. In this data two passengers have no Embarked value. Leaving them out would hide that gap, and the counts would no longer add up to the number of rows.
To see shares instead of counts, add normalize=True.
print(df["Embarked"].value_counts(normalize=True, dropna=False).round(3))
print(df["Pclass"].value_counts().sort_index())sort_index() orders the result by label instead of by frequency. This is useful for ordered categories such as Pclass, where 1, 2, 3 is the natural order.
Reading the counts
Check three things each time you count a column:
- Does the total match the number of rows? If not, missing values were dropped.
- Are any categories very small? A group of five passengers cannot support a firm conclusion.
- Do you see spelling variants, such as
"male"and"Male"? The Titanic file has none, but real files often do.
The table below summarizes the options you will use most.
| Call | What it shows |
|---|---|
| `value_counts()` | Counts, missing values excluded |
| `value_counts(dropna=False)` | Counts, with a row for missing values |
| `value_counts(normalize=True)` | Proportions that sum to 1 |
| `nunique()` | Number of distinct non-missing values |
Common errors
- Forgetting
dropna=Falseand concluding a column is complete. - Calling
value_counts()on a whole DataFrame instead of one column. Recent pandas versions count unique rows in that case, which is rarely what you want here. - Treating a high-cardinality column such as
NameorTicketas a category. Checknunique()first.
Exercise
Write code that prints the share of passengers in each Embarked port, including missing values, rounded to 3 decimals. Why would the shares differ if you left out dropna=False?
Show answer
Use print(df["Embarked"].value_counts(normalize=True, dropna=False).round(3)). Without dropna=False, the two missing rows are excluded from the denominator, so the three ports' shares are computed over 889 passengers instead of 891 and sum to 1. The shares come out slightly larger, and the gap in the data is hidden.
Exercise
Why is df["Pclass"].value_counts().sort_index() more readable than df["Pclass"].value_counts()?
Show answer
value_counts() sorts by frequency, so the classes may appear as 3, 1, 2. sort_index() sorts by label, giving the natural order 1, 2, 3.