Sub topic 9
Summarizing text and categorical columns
This chapter assumes you know how to build a DataFrame, call head and info, and read the numeric output of describe. Here you will see what describe reports for columns that hold text or categories.
Why numeric statistics do not fit text
A mean or a quartile means nothing for a city name. For text, the useful questions are different. How many values are present? How many distinct values exist? Which value is most common, and how often does it appear?
describe answers these four questions with the rows count, unique, top, and freq.
| Row | Meaning |
|---|---|
| count | Number of non-missing values |
| unique | Number of distinct values |
| top | The most frequent value |
| freq | How many times `top` appears |
Describing one text column
This chapter uses the same DataFrame as earlier chapters.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli"],
"age": [34, 28, np.nan, 45, 39],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo"],
"salary": [52000, 48000, 61000, 75000, 58000],
})
print(df["city"].describe())Series.describe sees a non-numeric column and switches to the text summary. You get count 5 and unique 3, because the cities are Lima, Oslo, and Pune. Lima and Oslo each appear twice, so top is one of them and freq is 2.
Note that top is only one value when several values tie. If you need the full picture, use value_counts, covered below.
Describing every non-numeric column at once
A plain df.describe() skips text columns. To include them, you have two options.
print(df.describe(include="all"))
print(df.describe(exclude="number"))With include="all", numeric and text columns appear in one table. Each kind of column leaves the other's rows empty, shown as NaN. For example, city has no mean, and salary has no top. The table is wide and mostly sparse, so it is good for a quick scan.
With exclude="number", you get only the text columns, in a compact table of count, unique, top, and freq. This is usually easier to read when you only care about the text.
I use exclude="number" rather than include="object" because newer pandas versions can store text in a dedicated string dtype. Excluding numbers still selects those columns.
Categorical dtype
A column of repeated labels, such as city or status, can be stored as a category dtype. It uses less memory and signals that the values come from a small set.
cities = df["city"].astype("category")
print(cities.describe())
print(cities.dtype)The summary has the same four rows. The result for a categorical column looks like the one for text, so you do not need to learn a second format.
Looking past the single top value
describe shows only the leader. value_counts shows the whole distribution, and nunique counts distinct values directly.
print(df["city"].value_counts())
print(df["city"].value_counts(dropna=False))
print(df["name"].nunique())By default value_counts leaves out missing values. Passing dropna=False adds a row for them, which helps when a column has gaps. In this DataFrame city has no gaps, so both calls give the same result.
Reading the summary for problems
Compare count with the number of rows from df.shape. A smaller count means missing values. Then look at unique.
- If
uniqueequalscount, every value is different. That is expected for an identifier likename, but suspicious for a column that should hold categories. - If
uniqueis much larger than you expect, the labels may be inconsistent."Lima","lima", and"Lima "count as three values. - If
freqis close tocount, one value dominates and the column carries little information.
flowchart TD
A[Text column summary] --> B{count less than row count?}
B -- yes --> C[Missing values: check with isna]
B -- no --> D{unique larger than expected?}
D -- yes --> E[Inconsistent labels: check value_counts]
D -- no --> F{freq close to count?}
F -- yes --> G[One value dominates]
F -- no --> H[Column looks reasonable]Replace the opening fence of the diagram above with the diagram fence format in your own notes if you copy it. The flow itself is what matters: compare count, then unique, then freq.
Exercise
A column status in a 1,000-row DataFrame shows count 940, unique 7, top "active", freq 910 in describe. You expected only three statuses: active, inactive, and pending. What two problems does the summary suggest, and which method do you call next?
Show answer
The count of 940 against 1,000 rows means 60 values are missing. A unique value of 7 against the expected 3 suggests inconsistent labels, such as different spellings or capitalization. Call df["status"].value_counts(dropna=False) to see every variant and the missing values.