Sub topic 9
Summarizing text and categorical columns
This chapter assumes you have read the earlier chapters on head, info, and numeric describe. You should know that describe skips non-numeric columns by default, that include and exclude change that, and that info shows each column's dtype and non-null count. Here the focus is on what describe reports for text and categorical data, and on what those four numbers can and cannot tell you.
Why numeric statistics do not fit text
A mean of city names has no meaning, and neither does a 25th percentile of customer names. For these columns describe reports a different set of four statistics:
| Row | Meaning |
|---|---|
| `count` | Number of non-missing values |
| `unique` | Number of distinct non-missing values |
| `top` | The most frequent value (the mode) |
| `freq` | How many times `top` occurs |
These rows apply to columns with dtype object, category, and bool. In pandas 3 and later they also apply to the dedicated string dtype. Check df.dtypes first, because the dtype decides which summary you get.
A dataset with realistic mess
The examples below use a small orders table. It has a missing city and an inconsistent spelling, and tier is stored as a category.
import pandas as pd
orders = pd.DataFrame({
"customer": ["Ana", "Ben", "Cleo", "Ana", "Dev", "Ana", "Eli", "Ben"],
"city": ["Lima", "Oslo", "Lima", "lima ", "Pune", "Lima", None, "Oslo"],
"tier": ["gold", "basic", "basic", "gold", "basic", "gold", "basic", "basic"],
"amount": [120.5, 80.0, 45.0, 99.9, 60.0, 130.0, 55.5, 70.0],
})
orders["tier"] = orders["tier"].astype("category")
print(orders["city"].describe())Output:
count 7
unique 4
top Lima
freq 3
dtype: objectReading it line by line:
countis 7, not 8. TheNoneis not counted, so this matches the non-null count thatinfowould show.uniqueis 4:Lima,Oslo,lima(lowercase with a trailing space), andPune. A human sees three cities, but pandas sees four distinct strings.topisLima, which appears 3 times.dtype: objectdescribes the result Series, not the column. ASeries.describe()on text returns a Series of mixed values, so its own dtype isobject.
The unique value is the useful clue here. Three real cities would give unique of 3, so a value of 4 suggests a spelling or whitespace problem.
Summarizing a whole DataFrame
Pass include to ask for the non-numeric columns on a DataFrame.
print(orders.describe(include=["object", "category"]))Output:
customer city tier
count 8 7 8
unique 5 4 2
top Ana Lima basic
freq 3 3 5Each column is summarized independently. customer has 8 values and 5 distinct people, with Ana appearing 3 times. tier has two levels, and basic makes up 5 of 8 rows.
You can also select by exclusion. orders.describe(exclude="number") returns every column that is not numeric. This also catches bool and datetime columns, so it can return more than you expect.
If a DataFrame has no numeric columns at all, describe() with no arguments falls back to the count, unique, top, freq summary. You only need include when the frame mixes numeric and non-numeric columns.
Using include="all"
include="all" gives one table that covers every column.
print(orders.describe(include="all"))The result has the union of all rows: count, unique, top, freq, mean, std, min, the percentiles, and max. Each column fills only the rows that apply to it:
- Text and categorical columns show
NaNinmean,std,min, the percentiles, andmax. - Numeric columns show
NaNinunique,top, andfreq.
The table is compact but sparse. It also casts everything to a common object dtype, so numbers in the result are not suited to further arithmetic. For analysis, call describe separately on numeric and non-numeric subsets.
Categorical dtype specifics
A category column stores each distinct value once and keeps integer codes per row. Series.describe() on it reports the same four rows as on text:
print(orders["tier"].describe())Output:
count 8
unique 2
top basic
freq 5
Name: tier, dtype: objectTwo things to know:
- For categoricals,
uniquecounts values that actually occur. The dtype can also define categories that never appear in the data. Those are visible throughorders["tier"].cat.categories, and they are not counted inunique. - The summary does not show the order of an ordered categorical. If
tierhad a defined order such as basic < gold,describewould not tell you.
What the four numbers can tell you
You can read several data-quality signals from unique, top, and freq together with count.
Cardinality
Cardinality is the number of distinct values in a column. Compare unique to count:
uniqueclose tocountmeans almost every value is different. This is typical of identifiers, free text, and timestamps stored as strings. It is a poor candidate for grouping and a good candidate for a key.uniqueof 1 means the column is constant and carries no information for analysis.uniquemuch smaller thancountsuggests a real category. Consider converting it to thecategorydtype to save memory.
Dominance
The share of the most common value is freq / count. For tier that is 5/8, or 62.5%. A very high share, such as 99%, means the column is almost constant. Imbalance like this affects modeling and sampling later.
Inconsistent spellings
The city example showed unique of 4 where a person would count 3. Common causes:
- Different capitalization (
Lima,lima) - Leading or trailing whitespace (
"lima ") - Typos and abbreviations
- Different representations of missing data, such as
"N/A","-", or an empty string, whichdescribecounts as ordinary values
To see exactly which variants exist, use value_counts:
print(orders["city"].value_counts(dropna=False))dropna=False adds a row for missing values, which describe hides. After you identify the variants, you can normalize and re-check. Cleaning itself is outside this chapter, but a quick test is useful:
clean_city = orders["city"].str.strip().str.lower()
print(clean_city.describe())Output:
count 7
unique 3
top lima
freq 4
dtype: objectThe unique count dropped from 4 to 3 and the top count rose from 3 to 4. The missing value stays missing, because string methods pass NaN through unchanged.
Gotchas
Ties in top
When several values share the highest count, top reports one of them and freq reports the shared count. Which one is chosen is not something to rely on. In the original orders table, customer has Ana with 3 occurrences, so top is unambiguous there. A column where every value appears once reports one arbitrary value with freq of 1. If freq is low and unique is close to count, ignore top and use value_counts instead.
Numbers stored as text
A column of values like "12", "7", and "130" has dtype object. By default describe skips it, and with include="all" it gets a text summary where you wanted a mean. If a column you expected in the numeric summary is missing, check df.dtypes and convert with pd.to_numeric.
Missing values are invisible
count excludes missing values and unique ignores them. A column with 90% missing values can still show a neat unique and top. Always read count against the number of rows from df.shape or df.info().
Mixed types inside an object column
An object column can hold strings and numbers together. describe treats 1 and "1" as different values. A unique that is larger than expected can be a sign of this.
Dtype names vary by pandas version
Older versions store text as object. Newer versions can use a dedicated string dtype. If include=["object"] returns nothing on a column you know is text, print df.dtypes and adapt, or fall back to include="all" or exclude="number".
Using the summary in a first-look routine
Combine the pieces in this order for text columns:
- Run
df.info()to find text columns and their non-null counts. - Run
df.describe(include=["object", "category"])to getunique,top, andfreqfor each. - Flag columns where
uniqueis nearcount(identifiers), whereuniqueis 1 (constants), or wherefreq / countis very high (dominance). - For each flagged column, run
value_counts(dropna=False)to see the real values.
Exercise
A column status has count 500, unique 7, top "active", freq 480. The business says there should be only 3 statuses. What do the numbers suggest, and what is your next step?
Show answer
Seven distinct values where three are expected points to spelling, case, whitespace, or placeholder variants. The top value "active" covers 96% of rows (480/500), so the other six values are rare. Run df["status"].value_counts(dropna=False) to list them, decide which to merge or treat as missing, and then re-run describe to confirm unique is 3.
Exercise
You call df.describe() on a table with columns id (int), name (text), and score (float). The result has columns id and score only. Write one call that adds name to the output, and say which rows will be NaN for score.
Show answer
Use df.describe(include="all"). The unique, top, and freq rows will be NaN for score, because those statistics only apply to non-numeric columns. The name column will have NaN in mean, std, min, the percentile rows, and max.