Sub topic 8
Choosing columns with include and exclude
By default, DataFrame.describe() summarizes numeric columns and silently skips the rest. This chapter covers the include and exclude arguments, which change which columns are summarized. It also covers the shape of the table that comes back and the errors you can hit.
This chapter assumes you can build a DataFrame and have used head, info, and plain describe(). You should also know that each column has a dtype, such as int64, float64, object, or category.
The default selection
Start with a small table that mixes dtypes. It extends the earlier example with a tier column stored as a categorical.
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],
"tier": pd.Categorical(["gold", "silver", "gold", "bronze", "silver"]),
})
print(df.describe().columns.tolist())This prints ['age', 'salary']. The columns name, city, and tier are missing from the report. Nothing warns you about that, so a quick describe() can give the impression that the whole table was summarized.
Two details matter later:
- If a DataFrame has no numeric columns at all, the default falls back to summarizing every column.
- Missing values are skipped.
agereports a count of 4, not 5, because one value isNaN.
Selecting by dtype with include
include takes a dtype selector or a list of them. Only columns that match are summarized.
print(df.describe(include="number").columns.tolist())
print(df.describe(include=[np.number]).columns.tolist())
print(df.describe(include="category").columns.tolist())The first two lines print ['age', 'salary']. They are equivalent: the string "number" and the NumPy type np.number select the same columns. The third line prints ['tier'].
You can pass a list to select several groups at once. A column is kept if it matches any entry in the list.
The common selectors are:
| Selector | Matches | Notes |
|---|---|---|
| `"number"` or `np.number` | integer, float, and complex columns | Does not match `bool` |
| `"object"` | columns with object dtype | Text stored the older way. See the callout on string dtypes below. |
| `"category"` | categorical columns | Reports count, unique, top, freq |
| `"datetime"` | datetime columns | Reports count, mean, min, quartiles, max |
| `"bool"` | boolean columns | Reports count, unique, top, freq |
| `"all"` | every column | Special value. Cannot be combined with `exclude`. |
You can also name exact dtypes, such as "int64" or "float64". A broad selector is usually easier to maintain, because a column that changes from int64 to float64 will still be matched.
Dropping dtypes with exclude
exclude works in the opposite direction. It summarizes everything except the matching dtypes. It is a good way to get "the non-numeric columns" without naming the text dtype.
text_report = df.describe(exclude="number")
print(text_report.columns.tolist())
print(text_report.index.tolist())The columns are ['name', 'city', 'tier'] and the rows are ['count', 'unique', 'top', 'freq']. Those four rows are the summary for non-numeric data:
countis the number of non-missing values.uniqueis the number of distinct values.topis the most common value.freqis how many timestopappears.
In city, Lima and Oslo each appear twice. When values tie, top reports only one of them, and you should not depend on which. A freq that is equal to the number of other values' frequencies tells you the tie exists.
A list works here too. df.describe(exclude=["number", "category"]) leaves only the plain text columns, name and city.
Summarizing everything with include="all"
include="all" puts every column into one table.
everything = df.describe(include="all")
print(everything.index.tolist())
print(everything.loc["unique"])The row labels are the union of the numeric and non-numeric statistics: count, unique, top, freq, mean, std, min, 25%, 50%, 75%, max. Each column fills in only the rows that make sense for it. In the unique row, city shows 3 and tier shows 3, and age and salary show NaN. In the mean row the pattern flips.
That NaN means "not applicable". It does not mean the data is missing. This matters when you read the table:
- A
NaNinmeanfor a text column is expected. - A
NaNinmeanfor a column you believed was numeric is a warning. The column is probably stored as text. Checkinfo()ordf.dtypes.
Because the table mixes types, every cell holds an object. The numbers in it are no longer plain floats in float columns, so do arithmetic on the report with care. If you want to use the numbers, build the numeric report separately with include="number".
Errors and edge cases
Two mistakes come up often. Both raise ValueError, so you can see them directly.
try:
df.describe(include="all", exclude="number")
except ValueError as err:
print(err)
try:
df.describe(include="datetime")
except ValueError as err:
print(err)The first message says that exclude must be None when include is 'all'. Choose one approach. If you want everything except some dtypes, drop include="all" and use exclude alone.
The second call finds no datetime columns in this table, so nothing is left to summarize. The message says a DataFrame without columns cannot be described. This is more likely than it sounds in code that loops over many files. A file that has no categorical column will fail on include="category", and your script stops. Guard such calls by checking for matching columns first, as shown in the helper later in this chapter.
A few other behaviors are worth knowing:
includeandexcludeare applied to dtypes, not to column names. To summarize chosen columns by name, select them first:df[["age", "salary"]].describe().- A selector that matches nothing in
excludeis harmless.df.describe(exclude="datetime")simply summarizes the defaults. Series.describe()acceptsincludeandexcludefor signature compatibility, but they have no effect on a single column. A Series is summarized according to its own dtype.- Boolean columns are not matched by
"number". They appear underinclude="all"orinclude="bool", with the count, unique, top, and freq rows.
Combining include with percentiles
The percentiles argument applies to numeric columns only, and it works together with include.
print(df.describe(include="number", percentiles=[0.1, 0.9]))The row labels are count, mean, std, min, 10%, 50%, 90%, max. The median (50%) is always included, even when you did not list it. If you use include="all" with percentiles, the extra quantile rows appear in the combined table, and text columns show NaN in them.
A reusable pattern: separate reports
A single include="all" table is convenient, but it can be wide and full of NaN. In scripts, two focused reports are easier to read. The helper below also avoids the empty-selection error.
def split_describe(frame):
reports = {}
if frame.select_dtypes(include="number").shape[1]:
reports["numeric"] = frame.describe(include="number")
if frame.select_dtypes(exclude="number").shape[1]:
reports["other"] = frame.describe(exclude="number")
return reports
for label, report in split_describe(df).items():
print(label)
print(report)
print()select_dtypes uses the same selector rules as describe. Using it first lets you test whether any columns match before you call describe. The result is a numeric report with count through max, and a second report with count, unique, top, and freq. For df, the numeric report covers age and salary. The other report covers name, city, and tier.
Checking your understanding
Exercise
You call df.describe(include="all", exclude="number") and get a ValueError. Rewrite the call so it summarizes every column except the numeric ones, and say why the original failed.
Show answer
Use df.describe(exclude="number"). The original failed because include="all" already selects every column, so pandas does not allow exclude to be set at the same time. Using exclude alone summarizes all dtypes except numeric ones.
Exercise
In the output of df.describe(include="all"), the "mean" cell for the city column is NaN, and the "mean" cell for salary has a value. A teammate says the NaN means city has missing data. Is that right? What would you check if "mean" were NaN for salary?
Show answer
No. The NaN in the mean row for a text column means the statistic does not apply to that dtype. Missing data shows up as a count lower than the number of rows. If mean were NaN for salary, the column is probably stored as text instead of numbers, so check df.dtypes or df.info() and convert it, for example with pd.to_numeric.
Exercise
A script runs df.describe(include="category") on many files, and it crashes on files with no categorical columns. How can you avoid the crash?
Show answer
Check whether any columns match before calling describe, for example with df.select_dtypes(include="category").shape[1] > 0, and only call describe when that is true. Without that check, describe raises a ValueError because it has no columns to summarize.