Sub topic 9
Summarising columns with describe and reductions
This chapter assumes you can build a DataFrame, select a column as a Series, and tell a Series from a DataFrame. It covers describe and the reduction methods (sum, mean, median and similar), which collapse a column into one number. The grouped summaries later in the tutorial are built from the same methods.
All examples use the sales DataFrame from earlier in the tutorial. It has six rows, and one units value is missing.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})What a reduction does
A reduction takes many values and returns fewer, usually one. Calling df["units"].sum() on a Series returns a single scalar. Calling df.sum() on a DataFrame applies the reduction to each column and returns a Series indexed by column name.
Common reductions
units = df["units"]
print(units.sum()) # 42.0
print(units.mean()) # 8.4
print(units.median()) # 8.0
print(units.min(), units.max()) # 5.0 12.0
print(round(units.std(), 2)) # 2.7
print(units.quantile(0.9)) # 11.2
print(df["region"].nunique()) # 3
print(units.idxmax()) # 4stdandvaruse the sample formula (divide by n - 1). Passddof=0for the population version.quantileinterpolates between neighbouring values by default. Forunits, the 0.9 position falls between 10 and 12, which gives 11.2.nuniquecounts distinct non-missing values.idxmaxandidxminreturn the index label of the extreme value, not the value itself. Usedf.loc[units.idxmax()]to fetch the whole row.
You can run several reductions in one call with agg and a list of names. The result is a Series whose index holds the function names.
print(df["units"].agg(["min", "median", "max"]))On a DataFrame, a reduction runs per column. A column with text in it breaks mean and sum in recent pandas versions, so restrict the call to numeric columns.
print(df[["units", "price"]].mean())
print(df.mean(numeric_only=True))Both calls return the same result: units is 8.4 and price is 3.25.
Missing values in reductions
Reductions skip missing values by default (skipna=True). That has three consequences:
meandivides by the number of non-missing values, sounits.mean()is 42 / 5, not 42 / 6.countcounts non-missing values only.len(df)andsizecount every row.sum(skipna=False)returnsNaNas soon as one value is missing.
print(len(df)) # 6
print(df["units"].count()) # 5
print(df["units"].isna().sum()) # 1
print(df["units"].sum(skipna=False)) # nanSkipping is usually what you want, but it changes the meaning of the result. An average over five of six rows is not an average over all orders. Compare len with count before you report a mean, so you know how many rows it used.
An all-missing column behaves differently for each reduction. sum returns 0 and mean returns NaN. If either result matters, check count() first.
describe: a standard summary in one call
describe returns a fixed set of statistics. For a numeric Series these are count, mean, std, min, the quartiles (25%, 50%, 75%) and max.
print(df["units"].describe())count 5.000000
mean 8.400000
std 2.701851
min 5.000000
25% 7.000000
50% 8.000000
75% 10.000000
max 12.000000
Name: units, dtype: float64The count of 5 is the first sign that a value is missing. The 50% row is the median, and the gap between mean and median hints at skew.
Choosing percentiles
Pass fractions between 0 and 1 to percentiles. The median is always included.
print(df["units"].describe(percentiles=[0.1, 0.9]))Describing a whole DataFrame
By default df.describe() summarises only the numeric columns and silently leaves out the text ones. That default can hide columns, so check which ones appear in the output.
print(df.describe())Use include="all" to describe every column. Statistics that do not apply to a column appear as NaN.
print(df.describe(include="all"))For text columns, describe reports different statistics: count, unique (distinct values), top (the most common value) and freq (how often top occurs). When two values tie for most common, top is not guaranteed to be a particular one, so do not rely on it. To summarise only the text columns, select them first.
print(df[["region", "product"]].describe())Choosing between describe and explicit reductions
| Need | Use |
|---|---|
| A quick look at a new numeric column | `describe()` |
| One number to store or compare | A named reduction such as `mean()` |
| A chosen set of statistics | `agg([...])` |
| A statistic `describe` lacks (sum, nunique, skew) | A named reduction |
| Category frequencies | `value_counts()`, covered next |
describe is for reading. Its output is a Series or DataFrame of formatted statistics. If you need one value in later code, call the reduction directly, for example df["units"].median(), rather than indexing into describe().
Common errors
- Reading
meanas an average over all rows when some values are missing. Checkcount(). - Expecting
df.describe()to include text columns. It does not unless you passinclude="all". - Calling
df.mean()on a frame with text columns and getting aTypeError. Select numeric columns or passnumeric_only=True. - Treating
idxmax()as the maximum value. It returns the label. - Comparing
stdfrom pandas with a population standard deviation from another tool. pandas defaults toddof=1, while NumPy'snp.stddefaults toddof=0.
Exercise
df["units"].mean() returns 8.4, but the six rows have a units total of 42. Why is the mean not 7.0, and how would you get 7.0 if you wanted it?
Show answer
The mean skips the missing value by default, so it divides 42 by 5 non-missing values, which gives 8.4. To treat the missing value as zero and divide by all six rows, fill it first: df["units"].fillna(0).mean() returns 7.0. Whether that is correct depends on whether a missing value really means zero units.
Exercise
What is the difference between df.describe() and df.describe(include="all") for the sales DataFrame?
Show answer
df.describe() reports only the numeric columns, units and price. include="all" adds region and product. For those text columns it reports unique, top and freq and leaves the numeric-only statistics as NaN.